package com.koron.tool.dialog;

import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

import com.koron.JavaSourceParserUtil;
import com.koron.tool.Constant;
import com.koron.tool.MainFrame;
import com.koron.tool.constant.SavedTableSetting;
import com.koron.tool.entity.Column;
import com.koron.tool.entity.ForeignKey;
import com.koron.tool.entity.Table;
import com.koron.tool.util.SerializeUtil;
import com.koron.tool.util.TableUtil;
import com.koron.ui.MutableGridLayout;
import com.koron.ui.TableParseAction;

import com.koron.util.StringUtils;
import com.sun.xml.internal.bind.v2.runtime.reflect.opt.Const;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import javafx.scene.layout.Pane;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;


@SuppressWarnings("serial")
public class OneKeyTableSqlBeanDialog extends JDialog {


    //各个数据在table model中对应的列的index

    public static final int COL_INDEX_DECORATOR = 0;
    public static final int COL_INDEX_TYPE = 1;
    public static final int COL_INDEX_COLUMN_NAME = 2;
    public static final int COL_INDEX_COLUMN_ALIAS = 3;
    public static final int COL_INDEX_PROPERTY_NAME = 4;
    public static final int COL_INDEX_REMARK = 5;
    public static final int COL_INDEX_IS_PRIMARY_KEY = 6;
    public static final int COL_INDEX_IS_AUTO_INCREASEMENT = 7;

    public static final int COL_INDEX_IS_SELECTED = 6;
    public static final int COL_INDEX_PK_TABLE_NAME = 7;
    public static final int COL_INDEX_FK_COLUMN_NAME = 8;
    public static final int COL_INDEX_PK_COLUMN_NAME = 9;


    public static final int TABLE_VIEW_COL_SIZE = 8;
    public static final int PK_TABLE_VIEW_COL_SIZE = 10;


    public static String CLASS_NAME_AUTOCODE = "AutoCode";

    public static String CLASS_SUFFIX_MAPPER = "Mapper";
    public static String CLASS_SUFFIX_DAO = "Dao";
    public static String CLASS_SUFFIX_SERVICE = "Service";
    public static String CLASS_SUFFIX_ACTION = "Controller";
    public static String CLASS_SUFFIX_BEAN = "";
    public static String CLASS_SUFFIX_SEARCHBEAN = "SearchBean";
    public static String CLASS_SUFFIX_VIEWBEAN = "ViewBean";


    public static String SEARCH_START_SUFFIX = "Start";

    public static String SEARCH_END_SUFFIX = "End";


    public static String SEARCH_LIST_SUFFIX = "List";


    //主表的信息
    private DefaultTableModel model = null;
    private JTable primaryTableView = null;

    //外键表的信息
    private List<DefaultTableModel> foreignTableModels = new ArrayList<DefaultTableModel>();
    private List<JTable> foreignTableViews = new ArrayList<JTable>();

    //外键表使用的别名
    private List<JTextField> foreignKeyTableAliasTextFields = new ArrayList<>();

    //选中需要保存的外键表的信息
    private List<ForeignKey> selectedForeignKeys = new ArrayList<>();


    //表名
    private String tableName;

    //表结构对象
    private Table table;


    //类名
    private JTextField jtfClass = new JTextField();

    private JTextField primaryTableAliasOne = new JTextField();

    private JTextField primaryTableAliasTwo = new JTextField();


    String autoCodeAnnotation = "@" + CLASS_NAME_AUTOCODE;
    String autoCodeReference = MainFrame.config.get(Constant.ANNOTATION_PACKAGE) + "." + CLASS_NAME_AUTOCODE;

    //包名
    private JTextField jtfPackage = new JTextField();
    private ResourceBundle resourceBuddle = ResourceBundle.getBundle(MainFrame.RESOURCEBUDDLE, getLocale());

    protected OneKeyTableSqlBeanDialog() {
    }

    public OneKeyTableSqlBeanDialog(final MainFrame frame) {
        this(frame, null);
    }

    public OneKeyTableSqlBeanDialog(final MainFrame frame, final Table table) {
        super(frame, "控制台信息", false);
        this.table = table;


        //显示控件
        setTitle("");


        //计算出控件显示的行数

        //整体显示两列
        //列表的页面，再进行合并成为1列

        int colNum = 2;

        //类名前缀需要一行展示
        //主表的字段需要用一行展示table
        //后面需要两行展示操作按钮
        int rowNum = 1 + 1 + 2;

        //获得外键表的数量
        //一个外键表需要占用两行
        //一行显示表名等信息
        //另一行显示表的字段信息
        rowNum += table.getForeignKeys().size() * 2;


        int windowHeight = 0;


        model = new DefaultTableModel(new String[]{
                resourceBuddle.getString("Decorator")
                , resourceBuddle.getString("Type")
                , "字段名"
                , "字段别名"
                , "属性名"
                , resourceBuddle.getString("Memo"),
                "是否主键",
                "是否自增"},
                0);
        primaryTableView = new JTable(model);


        //两列四行

        MutableGridLayout layout = new MutableGridLayout(colNum, rowNum, 5, 5);
        JPanel mainPanel = new JPanel(layout);
        JScrollPane mainScrollPane = new JScrollPane(mainPanel);


        //第一行也合并
        layout.merge(0, 0, 1, 0);

        //第二行的两列合并
        layout.merge(0, 1, 1, 1);


        //显示外键表信息的行也需要合并
        for (int i = 2; i < rowNum - 2; i++) {
            layout.merge(0, i, 1, i);
        }


        //第一行的高度为20
        layout.setHeight(0, 20);
        windowHeight += 20;
        //layout.setHeight(1, 20);

        //这里是操作按钮
        //倒数两行
        layout.setHeight(rowNum - 2, 20);
        layout.setHeight(rowNum - 1, 20);
        windowHeight += 40;

        //最外层使用一个滚动视图
        //1行1列
        MutableGridLayout singleLayout = new MutableGridLayout(1, 1, 5, 5);
        getContentPane().setLayout(singleLayout);

        // JScrollPane jScrollPane = new JScrollPane(getContentPane());
        // jScrollPane.setLayout(layout);
        //getContentPane().add(jScrollPane);


        //getContentPane().setLayout(layout);


//	      getContentPane().add(new JLabel("包名前缀"));
//	      getContentPane().add(jtfPackage);

        //添加外键需要的相关的组件,1行3列
        MutableGridLayout primaryTableSummaryLayout = new MutableGridLayout(3, 1, 5, 5);
        JPanel primaryTableSummaryPanel = new JPanel(primaryTableSummaryLayout);

        //label和text field组合
        //一行两列
        MutableGridLayout coupleLayout = new MutableGridLayout(2, 1, 5, 5);
        JPanel couplePannel = new JPanel(coupleLayout);
        couplePannel.add(new JLabel("类名前缀"));
        couplePannel.add(jtfClass);

        primaryTableSummaryPanel.add(couplePannel);


        //label和text field组合
        //一行两列
        coupleLayout = new MutableGridLayout(2, 1, 5, 5);
        couplePannel = new JPanel(coupleLayout);
        couplePannel.add(new JLabel("别名一"));
        if (!StringUtils.isEmpty(table.getTableAlias())) {
            primaryTableAliasOne.setText(table.getTableAlias());
        } else {
            primaryTableAliasOne.setText("s");
        }
        couplePannel.add(primaryTableAliasOne);
        primaryTableSummaryPanel.add(couplePannel);


        //label和text field组合
        //一行两列
        coupleLayout = new MutableGridLayout(2, 1, 5, 5);
        couplePannel = new JPanel(coupleLayout);
        couplePannel.add(new JLabel("别名二"));
        if (!StringUtils.isEmpty(table.getSecondTableAlias())) {
            primaryTableAliasTwo.setText(table.getSecondTableAlias());
        } else {
            primaryTableAliasTwo.setText("t");
        }

        couplePannel.add(primaryTableAliasTwo);

        primaryTableSummaryPanel.add(couplePannel);

        mainPanel.add(primaryTableSummaryPanel);


        jtfClass.addKeyListener(new KeyListener() {
            @Override
            public void keyTyped(KeyEvent e) {
            }

            @Override
            public void keyReleased(KeyEvent e) {
            }

            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {

                }
            }
        });


        primaryTableView.setRowHeight(25);
        primaryTableView.getColumnModel().getColumn(0).setCellEditor(new DefaultCellEditor(new JComboBox<>(new String[]{"", "public", "private", "protected"})));
        primaryTableView.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(new JComboBox<>(new String[]{"String", "Integer", "Boolean", "Double", "Date", "BigDecimal"})));
        primaryTableView.getColumnModel().getColumn(5).setCellEditor(new DefaultCellEditor(new JComboBox<>(new String[]{"N", "Y"})));
        primaryTableView.getColumnModel().getColumn(6).setCellEditor(new DefaultCellEditor(new JComboBox<>(new String[]{"N", "Y"})));
        primaryTableView.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        //构造data数组
        String[][] data = new String[table.getColumnCount()][TABLE_VIEW_COL_SIZE];
        int i = 0;
        for (Column column : table.getColumns()) {

            data[i][COL_INDEX_DECORATOR] = column.getDecorator();
            data[i][COL_INDEX_TYPE] = column.getType();
            data[i][COL_INDEX_COLUMN_NAME] = column.getColumnName();
            data[i][COL_INDEX_COLUMN_ALIAS] = column.getColumnAlias();
            data[i][COL_INDEX_PROPERTY_NAME] = column.getPropertyName();
            data[i][COL_INDEX_REMARK] = column.getRemark();
            data[i][COL_INDEX_IS_PRIMARY_KEY] = column.getPrimaryKey() ? "Y" : "N";
            data[i][COL_INDEX_IS_AUTO_INCREASEMENT] = column.getAutoIncreasement() ? "Y" : "N";
            i++;
        }


        if (data != null) {
            for (String[] strings : data) {
                model.addRow(strings);
            }
        }


        int height = (table.getColumnCount() + 1) * 26;
        if (height > 300) {
            height = 300;
        }

        windowHeight += 300;

        //jsp.setPreferredSize(new Dimension(200, height));
        primaryTableView.setSize(600, height);
        layout.setHeight(1, height);
        JScrollPane jsp = new JScrollPane(primaryTableView);
        jsp.setSize(600, height);

        mainPanel.add(jsp);


        //添加外键的表信息
        int count = 0;
        for (ForeignKey foreignKey : table.getForeignKeys()) {


            //添加一个静态文本框
            //  mainPanel.add(new JLabel("外键表名:"+foreignKey.getPkTable().getTableName()));

            //添加外键需要的相关的组件,1行5列
            MutableGridLayout foreignKeySummaryLayout = new MutableGridLayout(5, 1, 5, 5);
            JPanel foreignKeySummaryPanel = new JPanel(foreignKeySummaryLayout);
            foreignKeySummaryPanel.add(new JLabel("外键关联表表名:" + foreignKey.getPkTable().getTableName()));
            foreignKeySummaryPanel.add(new JLabel("外键字段名:" + foreignKey.getFkColumnName()));
            foreignKeySummaryPanel.add(new JLabel("外键关联字段名:" + foreignKey.getPkColumnName()));
            foreignKeySummaryPanel.add(new JLabel("外键关联表别名"));
            JTextField foreignKeyTableAliasTextField = new JTextField();
            foreignKeyTableAliasTextFields.add(foreignKeyTableAliasTextField);
            if (!StringUtils.isEmpty(foreignKey.getPkTable().getTableAlias())) {
                foreignKeyTableAliasTextField.setText(foreignKey.getPkTable().getTableAlias());
            } else {
                foreignKeyTableAliasTextField.setText("");
            }

            foreignKeySummaryPanel.add(foreignKeyTableAliasTextField);
            mainPanel.add(foreignKeySummaryPanel);

            //添加外键表的字段信息表

            DefaultTableModel foreignTableModel = new DefaultTableModel(new String[]{
                    resourceBuddle.getString("Decorator")
                    , resourceBuddle.getString("Type")
                    , "字段名"
                    , "字段别名"
                    , "属性名"
                    , resourceBuddle.getString("Memo")
                    , "是否选中"
                    , "pktablename"
                    , "fkcolumnname", "pkcolumnname"},
                    0);

            foreignTableModels.add(foreignTableModel);

            JTable foreignTableView = new JTable(foreignTableModel);


            foreignTableView.setRowHeight(25);
            foreignTableView.getColumnModel().getColumn(COL_INDEX_DECORATOR).setCellEditor(new DefaultCellEditor(new JComboBox<>(new String[]{"", "public", "private", "protected"})));
            foreignTableView.getColumnModel().getColumn(COL_INDEX_TYPE).setCellEditor(new DefaultCellEditor(new JComboBox<>(new String[]{"String", "Integer", "Boolean", "Double", "Date", "BigDecimal"})));
            foreignTableView.getColumnModel().getColumn(COL_INDEX_IS_SELECTED).setCellEditor(new DefaultCellEditor(new JComboBox<>(new String[]{"N", "Y"})));
            foreignTableView.getColumnModel().getColumn(COL_INDEX_PK_COLUMN_NAME).setMinWidth(0);
            foreignTableView.getColumnModel().getColumn(COL_INDEX_PK_COLUMN_NAME).setMaxWidth(0);

            foreignTableView.getColumnModel().getColumn(COL_INDEX_PK_TABLE_NAME).setMinWidth(0);
            foreignTableView.getColumnModel().getColumn(COL_INDEX_PK_TABLE_NAME).setMaxWidth(0);

            foreignTableView.getColumnModel().getColumn(COL_INDEX_FK_COLUMN_NAME).setMinWidth(0);
            foreignTableView.getColumnModel().getColumn(COL_INDEX_FK_COLUMN_NAME).setMaxWidth(0);

            //foreignTableView.getColumnModel().getColumn(6).setCellEditor(new DefaultCellEditor(new JComboBox<>(new String[]{"N","Y"})));
            foreignTableView.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

            foreignTableViews.add(foreignTableView);


            data = new String[foreignKey.getPkTable().getColumnCount()][PK_TABLE_VIEW_COL_SIZE];
            i = 0;

            for (Column column : foreignKey.getPkTable().getColumns()) {

                data[i][COL_INDEX_DECORATOR] = column.getDecorator();
                data[i][COL_INDEX_TYPE] = column.getType();
                data[i][COL_INDEX_COLUMN_NAME] = column.getColumnName();

//                data[i][COL_INDEX_COLUMN_ALIAS]=column.getColumnAlias();
//                data[i][COL_INDEX_PROPERTY_NAME]=column.getPropertyName();
                if (!StringUtils.isEmpty(column.getColumnAlias())) {
                    data[i][COL_INDEX_COLUMN_ALIAS] = column.getColumnAlias();
                } else {
                    data[i][COL_INDEX_COLUMN_ALIAS] = "";
                }

                if (!StringUtils.isEmpty(column.getPropertyName())) {
                    data[i][COL_INDEX_PROPERTY_NAME] = column.getPropertyName();
                } else {
                    data[i][COL_INDEX_PROPERTY_NAME] = "";
                }

                data[i][COL_INDEX_REMARK] = column.getRemark();
                if (Boolean.TRUE.equals(column.getForeignColumnSelected())) {
                    data[i][COL_INDEX_IS_SELECTED] = "Y";
                } else {
                    data[i][COL_INDEX_IS_SELECTED] = "N";
                }

                data[i][COL_INDEX_PK_TABLE_NAME] = foreignKey.getPkTable().getTableName();
                data[i][COL_INDEX_FK_COLUMN_NAME] = foreignKey.getFkColumnName();
                data[i][COL_INDEX_PK_COLUMN_NAME] = foreignKey.getPkColumnName();

                i++;
            }


            if (data != null) {
                for (String[] strings : data) {
                    foreignTableModel.addRow(strings);
                }
            }
            jsp = new JScrollPane(foreignTableView);

            //jsp.setPreferredSize(new Dimension(200, 200));
            foreignTableView.setSize(600, 200);
            jsp.setSize(600, 200);
            windowHeight += 225;
            //显示标签的高度
            layout.setHeight(2 + 2 * count, 25);
            layout.setHeight(2 + 2 * count + 1, 200);
            //显示表格的高度

            ++count;
            mainPanel.add(jsp);

        }


        JButton btnAdd = new JButton(resourceBuddle.getString("AddLine"));
        btnAdd.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int pos = primaryTableView.getSelectedRow();
                if (pos == -1) {
                    model.addRow(new String[]{"private", "String", "", "", "", "N", "N"});
                } else {
                    model.insertRow(pos + 1, new String[]{"private", "String", "", "", "", "N", "N"});
                }
            }
        });
        mainPanel.add(btnAdd);
        JButton btnRemove = new JButton(resourceBuddle.getString("RemoveLine"));
        btnRemove.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int pos = primaryTableView.getSelectedRow();
                if (pos == -1) {
                    model.setRowCount(model.getRowCount() - 1);
                } else {
                    int rows = model.getRowCount();
                    model.removeRow(pos);
                    model.setRowCount(rows - 1);
                }
            }
        });
        mainPanel.add(btnRemove);
        JButton btnSave = new JButton(resourceBuddle.getString("Save"));
        btnSave.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {



			    /*生成bean文件*/
                try {

                    selectedForeignKeys.clear();
                    // int i = 0;
                    //处理需要关联的外键的信息
                    for (int j = 0; j < foreignTableModels.size(); j++) {
                        //for(TableModel tableModel:foreignTableModels){
                        TableModel tableModel = foreignTableModels.get(j);


                        ForeignKey foreignKey = new ForeignKey();
                        foreignKey.setFkColumnName(tableModel.getValueAt(0, COL_INDEX_FK_COLUMN_NAME).toString());
                        Table pkTable = new Table();
                        pkTable.setTableName(tableModel.getValueAt(0, COL_INDEX_PK_TABLE_NAME).toString());

                        pkTable.setTableAlias(foreignKeyTableAliasTextFields.get(j).getText());
                        foreignKey.setPkColumnName(tableModel.getValueAt(0, COL_INDEX_PK_COLUMN_NAME).toString());
                        foreignKey.setPkTable(pkTable);
                        int selectedCount = 0;
                        for (int i = 0; i < tableModel.getRowCount(); i++) {
                            //判断第6列是否为Y
                            if ("Y".equals(tableModel.getValueAt(i, COL_INDEX_IS_SELECTED).toString())) {
                                Column pkColumn = new Column();
                                pkColumn.setColumnName(tableModel.getValueAt(i, COL_INDEX_COLUMN_NAME).toString());

                                //别名不能为空
                                if (StringUtils.isEmpty(tableModel.getValueAt(i, COL_INDEX_COLUMN_ALIAS).toString())) {
                                    JOptionPane.showMessageDialog(frame, pkTable.getTableName() + "." + pkColumn.getColumnName() + "的列表别名不能为空!");
                                    return;
                                }

                                pkColumn.setColumnAlias(tableModel.getValueAt(i, COL_INDEX_COLUMN_ALIAS).toString());
                                pkColumn.setDecorator(tableModel.getValueAt(i, COL_INDEX_DECORATOR).toString());

                                //属性名也不能为空
                                if (StringUtils.isEmpty(tableModel.getValueAt(i, COL_INDEX_PROPERTY_NAME).toString())) {
                                    JOptionPane.showMessageDialog(frame, pkTable.getTableName() + "." + pkColumn.getColumnName() + "的属性名不能为空!");
                                    return;
                                }
                                pkColumn.setPropertyName(tableModel.getValueAt(i, COL_INDEX_PROPERTY_NAME).toString());
                                pkColumn.setRemark(tableModel.getValueAt(i, COL_INDEX_REMARK).toString());
                                pkColumn.setType(tableModel.getValueAt(i, COL_INDEX_TYPE).toString());
                                pkColumn.setForeignColumnSelected(true);
                                pkTable.addColumn(pkColumn);
                                selectedCount += 1;
                            }

                        }
                        if (selectedCount > 0) {
                            if (StringUtils.isEmpty(foreignKeyTableAliasTextFields.get(j).getText())) {
                                JOptionPane.showMessageDialog(frame, pkTable.getTableName() + "的表别名不能为空!");
                                return;
                            }

                            selectedForeignKeys.add(foreignKey);
                        }
                    }

                    //将用户对该表的配置信息存放到数据库表中
                    Table savedTable = new Table();
                    savedTable.setTableName(tableName);

                    //保存各个列的信息


                    //保存选择的外键的信息
                    savedTable.setForeignKeys(selectedForeignKeys);

                    Map<String, Table> foreignKeyMap = new HashMap<String, Table>();
                    for (ForeignKey foreignKey : selectedForeignKeys) {
                        foreignKeyMap.put(foreignKey.getFkColumnName(), foreignKey.getPkTable());
                    }

                    savedTable.setForeignKeyMap(foreignKeyMap);


                    //保存到数据库中
                    saveTableSetting(savedTable);

                    //处理auto code注解,如果没有的话，则添加


                    checkAutoCodeAnnotation(e, frame);

                    generateBeanFile(e, frame);

			    /*生成searchbean文件*/
                    generateSearchBean(e, frame);

			    /*生成viewbean*/
                    generateViewBean(e, frame);

			    /*生成mybatis xml文件*/
                    generateMybatisFile(e, frame);

			    /*生成mapper文件*/
                    generateMapperFile(e, frame);

                    generateDaoFile(e, frame);

                    generateServiceFile(e, frame);

			    /*生成action 文件*/
                    //generateActionFile(e,frame);


                    JOptionPane.showMessageDialog(frame, resourceBuddle.getString("SaveSuccess"));
                } catch (Throwable t) {
                    JOptionPane.showMessageDialog(frame, resourceBuddle.getString("SaveFail"));
                }

            }
        });
        mainPanel.add(btnSave);
        JButton btnClose = new JButton(resourceBuddle.getString("Close"));
        btnClose.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });
        mainPanel.add(btnClose);

        windowHeight += 100;

        windowHeight = 600;
        getContentPane().add(mainScrollPane);

        setSize(800, windowHeight);
        Point p = frame.getLocationOnScreen();
        p.x = p.x + (frame.getWidth() - getWidth()) / 2;
        p.y = p.y + (frame.getHeight() - getHeight()) / 2;
        setLocation(p);


        // this(frame,data);
        //this.tableName=tableName;
        this.tableName = table.getTableName();
        //根据表名，计算出类名
        String[] tableNameSplitArray = tableName.split("_");
        //第一个是前缀，忽略
        String className = "";
        for (i = 1; i < tableNameSplitArray.length; i++) {
            className += firstUpper(tableNameSplitArray[i]);
        }
        jtfClass.setText(className);

    }

    private String generateTableAlias(String tableName) {
        int pos = tableName.indexOf("_");
        if (pos < 0) {
            return "alias_" + tableName;
        } else {
            return tableName.substring(tableName.indexOf("_") + 1);
        }

    }

    private void saveTableSetting(Table savedTable) {

        try {
            //序列化
            String tableName = savedTable.getTableName();
            byte[] data = SerializeUtil.writeObject(savedTable);
            Connection conn = MainFrame.getConnection(MainFrame.config.get(Constant.DATABASE_ALIAS));
            //查询表是否存在，不存在则创建


            String sql = "CREATE TABLE  if not exists  `tbl_code_generator_setting` (" +
                    "  `table_name` varchar(100) NOT NULL," +
                    "  `data` longblob NOT NULL," +
                    "  PRIMARY KEY (`table_name`)" +
                    ")";

            Statement statement = conn.createStatement();
            statement.executeUpdate(sql);


            //查询记录是否存在
            sql = "select * from tbl_code_generator_setting where `table_name` = ?";
            PreparedStatement preparedStatement = conn.prepareStatement(sql);
            preparedStatement.setString(1, savedTable.getTableName());

            ResultSet resultSet = preparedStatement.executeQuery();

            if (resultSet.next()) {

                //执行update
                sql = "update " + SavedTableSetting.TABLE_NAME + " set data = ? where table_name = ? ";
                preparedStatement = conn.prepareStatement(sql);
                preparedStatement.setBytes(1, data);
                preparedStatement.setString(2, tableName);
                preparedStatement.executeUpdate();


            } else {
                sql = "insert into " + SavedTableSetting.TABLE_NAME + " ( `data`,`table_name` ) values(?,?)";
                preparedStatement = conn.prepareStatement(sql);
                preparedStatement.setBytes(1, data);
                preparedStatement.setString(2, tableName);
                preparedStatement.executeUpdate();

            }


        } catch (Throwable t) {
            throw new RuntimeException(t);
        }


    }

//	public OneKeyTableSqlBeanDialog(final MainFrame frame,String[][] data)
//	{
//
//	}


    private void generateServiceFile(ActionEvent e, MainFrame frame) throws Throwable {

        //根据flag判断是否需要生成service
        if (!"Y".equals(MainFrame.config.get(Constant.SERVICE_GENERATE_FLAG))) {
            return;
        }

        if (jtfClass.getText().equals("")) {
            JOptionPane.showMessageDialog(frame, resourceBuddle.getString("InputClassName"));
            jtfClass.requestFocus();
        } else if (model.getRowCount() == 0) {
            JOptionPane.showMessageDialog(frame, resourceBuddle.getString("NoData"));
        }
//        else if(jtfPackage.getText().equals(""))
//        {
//            JOptionPane.showMessageDialog(frame, "输入包名");
//            jtfPackage.requestFocus();
//        }
        else {
            StringBuilder sb = new StringBuilder();
            String classStr = jtfClass.getText();
            if (classStr.endsWith(".java")) {
                classStr = classStr.substring(0, classStr.indexOf(".java"));
            }

            //class名中不能包含包名
            if (classStr.indexOf('.') >= 0) {
                JOptionPane.showMessageDialog(frame, "类名中不能包含包名!");
                jtfClass.requestFocus();
                return;
            }

            //String packageStr = jtfPackage.getText();
            String packageStr = MainFrame.config.get(Constant.SERVICE_PACKAGE);

            //action的包名需要加上servlet;
            String oriPackageStr = packageStr;
            //packageStr+="."+PACKAGE_PREFIX_MAPPER;

            //需要通过最初的classname来拼接其他类型的类的名称
            String oriClassStr = classStr;
            //类名需要加上Action后缀
            classStr += CLASS_SUFFIX_SERVICE;


            //获取原来文件中需要保留的信息
            String filePath = MainFrame.config.get(Constant.SERVICE_SRC_PATH);
            filePath += File.separator + packageStr.replace('.', File.separatorChar) + File.separator + classStr + ".java";
            Map<String, List<String>> savedMap = JavaSourceParserUtil.getNotAutoCode(filePath);
            List<String> savedImports = savedMap.get("import");
            if (savedImports == null) {
                savedImports = new ArrayList<String>();
            }

            List<String> savedFields = savedMap.get("field");
            if (savedFields == null) {
                savedFields = new ArrayList<String>();
            }

            List<String> savedMethods = savedMap.get("method");
            if (savedMethods == null) {
                savedMethods = new ArrayList<String>();
            }

            sb.append("package ").append(packageStr).append(";\n");



            /*
             * 导入相关的类
             * */
            sb.append("import java.util.List;\n");
            //sb.append("import org.apache.ibatis.annotations.Param;\n");

            sb.append("import " + MainFrame.config.get(Constant.BEAN_PACKAGE) + "." + oriClassStr + CLASS_SUFFIX_BEAN + ";\n");
            sb.append("import " + MainFrame.config.get(Constant.SEARCH_BEAN_PACKAGE) + "." + oriClassStr + CLASS_SUFFIX_SEARCHBEAN + ";\n");
            sb.append("import " + MainFrame.config.get(Constant.VIEW_BEAN_PACKAGE) + "." + oriClassStr + CLASS_SUFFIX_VIEWBEAN + ";\n");
            sb.append("import " + MainFrame.config.get(Constant.DAO_PACKAGE) + "." + oriClassStr + CLASS_SUFFIX_DAO + ";\n");
            sb.append("import org.springframework.stereotype.Service;\n");
            sb.append("import org.springframework.beans.factory.annotation.Autowired;\n");
            sb.append("import " + autoCodeReference + ";\n");

            for (String str : savedImports) {
                sb.append(str);
            }


            //找出主键,只能有一个主键
            String keyProperty = null;
            int keyPropertyCount = 0;
            String keyPreopertyType = null;
            for (int i = 0; i < model.getRowCount(); i++) {
                //判断第5个字段的值是否为Y
                if (model.getValueAt(i, COL_INDEX_IS_PRIMARY_KEY).equals("Y")) {
                    keyProperty = model.getValueAt(i, COL_INDEX_PROPERTY_NAME).toString();
                    keyPropertyCount++;
                    keyPreopertyType = model.getValueAt(i, COL_INDEX_TYPE).toString();
                }
            }

            //主键数量多余一个，报错
            if (keyPropertyCount > 1) {
                JOptionPane.showMessageDialog(frame, "主键数量不能多余一个!");
                return;
            }

            sb.append("@Service\n");
            sb.append("public class ").append(classStr).append("\n{\n");

            String daoClass = oriClassStr + CLASS_SUFFIX_DAO;
//            sb.append("\t"+autoCodeAnnotation+"\n");
            sb.append("\t@Autowired\n");
            sb.append("\t" + autoCodeAnnotation + "\n");
            //定义mapper
            sb.append("\tprivate " + daoClass + " dao;\n\n");

            for (String str : savedFields) {
                sb.append("\t" + str);
            }

            for (String str : savedMethods) {
                sb.append("\t" + str);
            }

            //定义add 接口
            sb.append("\t" + autoCodeAnnotation + "\n");
            sb.append("\tpublic Integer add").append(oriClassStr).append("(" + oriClassStr + CLASS_SUFFIX_BEAN + " bean){\n");
            sb.append("\t\treturn dao.add" + oriClassStr + "(bean);\n");
            sb.append("\t}\n\n");


            //定义addSelective接口
            sb.append("\t" + autoCodeAnnotation + "\n");
            sb.append("\tpublic Integer add").append(oriClassStr).append("Selective").append("(" + oriClassStr + CLASS_SUFFIX_BEAN + " bean){\n");
            sb.append("\t\treturn dao.add" + oriClassStr + "Selective(bean);\n");
            sb.append("\t}\n\n");
            //定义del接口
            if (keyProperty != null) {
                sb.append("\t" + autoCodeAnnotation + "\n");
                sb.append("\tpublic Integer del").append(oriClassStr).append("(" + keyPreopertyType + " " + convertColNameToHumpStyle(keyProperty) + "){\n");
                sb.append("\t\t return dao.del" + oriClassStr + "(" + convertColNameToHumpStyle(keyProperty) + ");\n");
                sb.append("\t}\n\n");
            }

            //定义delWithClause接口
            sb.append("\t" + autoCodeAnnotation + "\n");
            sb.append("\tpublic Integer del").append(oriClassStr).append("WithClause").append("( " + oriClassStr + CLASS_SUFFIX_SEARCHBEAN + " searchBean){\n");
            sb.append("\t\t return dao.del" + oriClassStr + "WithClause" + "(searchBean);\n");
            sb.append("\t}\n\n");


            if (keyProperty != null) {
                //定义update接口
                sb.append("\t" + autoCodeAnnotation + "\n");
                sb.append("\tpublic Integer update").append(oriClassStr).append("(" + oriClassStr + CLASS_SUFFIX_BEAN + " bean){\n");
                sb.append("\t\t return dao.update" + oriClassStr + "(bean);\n");
                sb.append("\t}\n\n");
            }


            if (keyProperty != null) {
                //定义updateSelective接口
                sb.append("\t" + autoCodeAnnotation + "\n");
                sb.append("\tpublic Integer update").append(oriClassStr).append("Selective").append("(" + oriClassStr + CLASS_SUFFIX_BEAN + " bean){\n");
                sb.append("\t\t return dao.update" + oriClassStr + "Selective(bean);\n");
                sb.append("\t}\n\n");

                sb.append("\t" + autoCodeAnnotation + "\n");
                sb.append("\tpublic Integer increaseUpdate").append(oriClassStr).append("Selective").append("(" + oriClassStr + CLASS_SUFFIX_BEAN + " bean){\n");
                sb.append("\t\t return dao.increaseUpdate" + oriClassStr + "Selective(bean);\n");
                sb.append("\t}\n\n");

            }


            //定义updateSelectiveWithClause
            sb.append("\t" + autoCodeAnnotation + "\n");
            sb.append("\tpublic Integer update").append(oriClassStr).append("SelectiveWithClause").append("(" + oriClassStr + CLASS_SUFFIX_BEAN + " bean," + oriClassStr + CLASS_SUFFIX_SEARCHBEAN + " searchBean){\n");
            sb.append("\t\t return dao.update" + oriClassStr + "SelectiveWithClause(bean,searchBean);\n");
            sb.append("\t}\n\n");

            sb.append("\t" + autoCodeAnnotation + "\n");
            sb.append("\tpublic Integer increaseUpdate").append(oriClassStr).append("SelectiveWithClause").append("(" + oriClassStr + CLASS_SUFFIX_BEAN + " bean," + oriClassStr + CLASS_SUFFIX_SEARCHBEAN + " searchBean){\n");
            sb.append("\t\t return dao.increaseUpdate" + oriClassStr + "SelectiveWithClause(bean,searchBean);\n");
            sb.append("\t}\n\n");


            //定义list接口
            sb.append("\t" + autoCodeAnnotation + "\n");
            sb.append("\tpublic List<" + oriClassStr + CLASS_SUFFIX_VIEWBEAN + "> list").append("(" + oriClassStr + CLASS_SUFFIX_SEARCHBEAN + " bean){\n");
            sb.append("\t\treturn dao.list(bean);\n");
            sb.append("\t}\n\n");
            //定义list count接口
            sb.append("\t" + autoCodeAnnotation + "\n");
            sb.append("\tpublic Integer listCount").append("(" + oriClassStr + CLASS_SUFFIX_SEARCHBEAN + " bean){\n");
            sb.append("\t\treturn dao.listCount(bean);\n");
            sb.append("}\n\n");

            //定义listOne接口
            sb.append("\t" + autoCodeAnnotation + "\n");
            sb.append("\tpublic " + oriClassStr + CLASS_SUFFIX_VIEWBEAN + " listOne").append("(" + oriClassStr + CLASS_SUFFIX_SEARCHBEAN + " bean){\n");
            sb.append("\t\tList<" + oriClassStr + CLASS_SUFFIX_VIEWBEAN + ">list =  dao.list(bean);\n");
            sb.append("\t\tif(list == null || list.isEmpty()){\n");
            sb.append("\t\t  return null;\n");
            sb.append("\t\t};\n");
            sb.append("\t\treturn list.get(0);\n");

            sb.append("}\n\n");


            //定义getby主键接口
            if (keyProperty != null) {
                sb.append("\t" + autoCodeAnnotation + "\n");
                sb.append("\tpublic ").append(oriClassStr + CLASS_SUFFIX_VIEWBEAN).append(" getBy").append(convertColNameToHumpStyleWithFirstUpper(keyProperty)).append("(" + keyPreopertyType + " " + convertColNameToHumpStyle(keyProperty) + "){\n");
                sb.append("\t\treturn dao.").append("getBy").append(convertColNameToHumpStyleWithFirstUpper(keyProperty)).append("(").append(convertColNameToHumpStyle(keyProperty)).append(");\n");
                sb.append("\t}\n\n");
            }

            //定义wrap方法，用于处理结果集中常量展示的包装


            sb.append("\n}");
            File f = new File(MainFrame.config.get(Constant.SERVICE_SRC_PATH));
            f = new File(f, packageStr.replace('.', File.separatorChar));
            if (!f.exists())
                f.mkdirs();
            f = new File(f, classStr + ".java");
            try {
                PrintWriter fw = new PrintWriter(f, MainFrame.config.get(Constant.ENCODE));
                fw.append(sb.toString());
                fw.close();

            } catch (IOException e1) {

                e1.printStackTrace();
                throw e1;
            }
        }


    }


    private void generateDaoFile(ActionEvent e, MainFrame frame) throws Throwable {

        if (jtfClass.getText().equals("")) {
            JOptionPane.showMessageDialog(frame, resourceBuddle.getString("InputClassName"));
            jtfClass.requestFocus();
        } else if (model.getRowCount() == 0) {
            JOptionPane.showMessageDialog(frame, resourceBuddle.getString("NoData"));
        }
//        else if(jtfPackage.getText().equals(""))
//        {
//            JOptionPane.showMessageDialog(frame, "输入包名");
//            jtfPackage.requestFocus();
//        }
        else {
            StringBuilder sb = new StringBuilder();
            String classStr = jtfClass.getText();
            if (classStr.endsWith(".java")) {
                classStr = classStr.substring(0, classStr.indexOf(".java"));
            }

            //class名中不能包含包名
            if (classStr.indexOf('.') >= 0) {
                JOptionPane.showMessageDialog(frame, "类名中不能包含包名!");
                jtfClass.requestFocus();
                return;
            }

            //String packageStr = jtfPackage.getText();
            String packageStr = MainFrame.config.get(Constant.DAO_PACKAGE);

            //action的包名需要加上servlet;
            String oriPackageStr = packageStr;
            //packageStr+="."+PACKAGE_PREFIX_MAPPER;

            //需要通过最初的classname来拼接其他类型的类的名称
            String oriClassStr = classStr;
            //类名需要加上Action后缀
            classStr += CLASS_SUFFIX_DAO;


            //获取原来文件中需要保留的信息
            String filePath = MainFrame.config.get(Constant.SRC_ROOT_PATH);
            filePath += File.separator + packageStr.replace('.', File.separatorChar) + File.separator + classStr + ".java";
            Map<String, List<String>> savedMap = JavaSourceParserUtil.getNotAutoCode(filePath);
            List<String> savedImports = savedMap.get("import");
            if (savedImports == null) {
                savedImports = new ArrayList<String>();
            }

            List<String> savedFields = savedMap.get("field");
            if (savedFields == null) {
                savedFields = new ArrayList<String>();
            }

            List<String> savedMethods = savedMap.get("method");
            if (savedMethods == null) {
                savedMethods = new ArrayList<String>();
            }

            sb.append("package ").append(packageStr).append(";\n");



            /*
             * 导入相关的类
             * */
            sb.append("import java.util.List;\n");
            //sb.append("import org.apache.ibatis.annotations.Param;\n");

            sb.append("import " + MainFrame.config.get(Constant.BEAN_PACKAGE) + "." + oriClassStr + CLASS_SUFFIX_BEAN + ";\n");
            sb.append("import " + MainFrame.config.get(Constant.SEARCH_BEAN_PACKAGE) + "." + oriClassStr + CLASS_SUFFIX_SEARCHBEAN + ";\n");
            sb.append("import " + MainFrame.config.get(Constant.VIEW_BEAN_PACKAGE) + "." + oriClassStr + CLASS_SUFFIX_VIEWBEAN + ";\n");
            sb.append("import " + MainFrame.config.get(Constant.MAPPER_PACKAGE) + "." + oriClassStr + CLASS_SUFFIX_MAPPER + ";\n");
            sb.append("import org.springframework.stereotype.Repository;\n");
            sb.append("import org.springframework.beans.factory.annotation.Autowired;\n");
            sb.append("import " + autoCodeReference + ";\n");

            for (String str : savedImports) {
                sb.append(str);
            }


            //找出主键,只能有一个主键
            String keyProperty = null;
            int keyPropertyCount = 0;
            String keyPreopertyType = null;
            for (int i = 0; i < model.getRowCount(); i++) {
                //判断第5个字段的值是否为Y
                if (model.getValueAt(i, COL_INDEX_IS_PRIMARY_KEY).equals("Y")) {
                    keyProperty = model.getValueAt(i, COL_INDEX_PROPERTY_NAME).toString();
                    keyPropertyCount++;
                    keyPreopertyType = model.getValueAt(i, COL_INDEX_TYPE).toString();
                }
            }

            //主键数量多余一个，报错
            if (keyPropertyCount > 1) {
                JOptionPane.showMessageDialog(frame, "主键数量不能多余一个!");
                return;
            }

            sb.append("@Repository\n");
            sb.append("public class ").append(classStr).append("\n{\n");

            String mapperClass = oriClassStr + CLASS_SUFFIX_MAPPER;
//            sb.append("\t"+autoCodeAnnotation+"\n");
            sb.append("\t@Autowired\n");
            sb.append("\t" + autoCodeAnnotation + "\n");
            //定义mapper
            sb.append("\tprivate " + mapperClass + " mapper;\n\n");

            for (String str : savedFields) {
                sb.append("\t" + str);
            }

            for (String str : savedMethods) {
                sb.append("\t" + str);
            }

            //定义add 接口
            sb.append("\t" + autoCodeAnnotation + "\n");
            sb.append("\tpublic Integer add").append(oriClassStr).append("(" + oriClassStr + CLASS_SUFFIX_BEAN + " bean){\n");
            sb.append("\t\treturn mapper.add" + oriClassStr + "(bean);\n");
            sb.append("\t}\n\n");


            //定义addSelective接口
            sb.append("\t" + autoCodeAnnotation + "\n");
            sb.append("\tpublic Integer add").append(oriClassStr).append("Selective").append("(" + oriClassStr + CLASS_SUFFIX_BEAN + " bean){\n");
            sb.append("\t\treturn mapper.add" + oriClassStr + "Selective(bean);\n");
            sb.append("\t}\n\n");
            //定义del接口
            if (keyProperty != null) {
                sb.append("\t" + autoCodeAnnotation + "\n");
                sb.append("\tpublic Integer del").append(oriClassStr).append("(" + keyPreopertyType + " " + convertColNameToHumpStyle(keyProperty) + "){\n");
                sb.append("\t\t return mapper.del" + oriClassStr + "(" + convertColNameToHumpStyle(keyProperty) + ");\n");
                sb.append("\t}\n\n");
            }

            //定义delWithClause接口
            sb.append("\t" + autoCodeAnnotation + "\n");
            sb.append("\tpublic Integer del").append(oriClassStr).append("WithClause").append("( " + oriClassStr + CLASS_SUFFIX_SEARCHBEAN + " searchBean){\n");
            sb.append("\t\t return mapper.del" + oriClassStr + "WithClause" + "(searchBean);\n");
            sb.append("\t}\n\n");


            if (keyProperty != null) {
                //定义update接口
                sb.append("\t" + autoCodeAnnotation + "\n");
                sb.append("\tpublic Integer update").append(oriClassStr).append("(" + oriClassStr + CLASS_SUFFIX_BEAN + " bean){\n");
                sb.append("\t\t return mapper.update" + oriClassStr + "(bean);\n");
                sb.append("\t}\n\n");
            }


            if (keyProperty != null) {
                //定义updateSelective接口
                sb.append("\t" + autoCodeAnnotation + "\n");
                sb.append("\tpublic Integer update").append(oriClassStr).append("Selective").append("(" + oriClassStr + CLASS_SUFFIX_BEAN + " bean){\n");
                sb.append("\t\t return mapper.update" + oriClassStr + "Selective(bean);\n");
                sb.append("\t}\n\n");

                sb.append("\t" + autoCodeAnnotation + "\n");
                sb.append("\tpublic Integer increaseUpdate").append(oriClassStr).append("Selective").append("(" + oriClassStr + CLASS_SUFFIX_BEAN + " bean){\n");
                sb.append("\t\t return mapper.increaseUpdate" + oriClassStr + "Selective(bean);\n");
                sb.append("\t}\n\n");

            }


            //定义updateSelectiveWithClause
            sb.append("\t" + autoCodeAnnotation + "\n");
            sb.append("\tpublic Integer update").append(oriClassStr).append("SelectiveWithClause").append("(" + oriClassStr + CLASS_SUFFIX_BEAN + " bean," + oriClassStr + CLASS_SUFFIX_SEARCHBEAN + " searchBean){\n");
            sb.append("\t\t return mapper.update" + oriClassStr + "SelectiveWithClause(bean,searchBean);\n");
            sb.append("\t}\n\n");

            sb.append("\t" + autoCodeAnnotation + "\n");
            sb.append("\tpublic Integer increaseUpdate").append(oriClassStr).append("SelectiveWithClause").append("(" + oriClassStr + CLASS_SUFFIX_BEAN + " bean," + oriClassStr + CLASS_SUFFIX_SEARCHBEAN + " searchBean){\n");
            sb.append("\t\t return mapper.increaseUpdate" + oriClassStr + "SelectiveWithClause(bean,searchBean);\n");
            sb.append("\t}\n\n");


            //定义list接口
            sb.append("\t" + autoCodeAnnotation + "\n");
            sb.append("\tpublic List<" + oriClassStr + CLASS_SUFFIX_VIEWBEAN + "> list").append("(" + oriClassStr + CLASS_SUFFIX_SEARCHBEAN + " bean){\n");
            sb.append("\t\treturn wrap(mapper.list(bean));\n");
            sb.append("\t}\n\n");
            //定义list count接口
            sb.append("\t" + autoCodeAnnotation + "\n");
            sb.append("\tpublic Integer listCount").append("(" + oriClassStr + CLASS_SUFFIX_SEARCHBEAN + " bean){\n");
            sb.append("\t\treturn mapper.listCount(bean);\n");
            sb.append("}\n\n");

            //定义listOne接口
            sb.append("\t" + autoCodeAnnotation + "\n");
            sb.append("\tpublic " + oriClassStr + CLASS_SUFFIX_VIEWBEAN + " listOne").append("(" + oriClassStr + CLASS_SUFFIX_SEARCHBEAN + " bean){\n");
            sb.append("\t\tList<" + oriClassStr + CLASS_SUFFIX_VIEWBEAN + ">list =  mapper.list(bean);\n");
            sb.append("\t\tif(list == null || list.isEmpty()){\n");
            sb.append("\t\t  return null;\n");
            sb.append("\t\t};\n");
            sb.append("\t\treturn wrap(list.get(0));\n");

            sb.append("}\n\n");


            //定义getby主键接口
            if (keyProperty != null) {
                sb.append("\t" + autoCodeAnnotation + "\n");
                sb.append("\tpublic ").append(oriClassStr + CLASS_SUFFIX_VIEWBEAN).append(" getBy").append(convertColNameToHumpStyleWithFirstUpper(keyProperty)).append("(" + keyPreopertyType + " " + convertColNameToHumpStyle(keyProperty) + "){\n");
                sb.append("\t\treturn wrap(mapper.").append("getBy").append(convertColNameToHumpStyleWithFirstUpper(keyProperty)).append("(").append(convertColNameToHumpStyle(keyProperty)).append("));\n");
                sb.append("\t}\n\n");
            }

            //定义wrap方法，用于处理结果集中常量展示的包装

            sb.append("\t" + autoCodeAnnotation + "\n");
            sb.append("\tpublic List<").append(oriClassStr + CLASS_SUFFIX_VIEWBEAN).append("> wrap(List<").append(oriClassStr + CLASS_SUFFIX_VIEWBEAN).append("> list){\n");
            sb.append("\t\tfor(").append(oriClassStr + CLASS_SUFFIX_VIEWBEAN).append(" viewbean:list){\n");
            sb.append("\t\t\twrap(viewbean);\n");
            sb.append("\t\t}\n");
            sb.append("\t\treturn list;\n");
            sb.append("\t}\n");

            sb.append("\t" + autoCodeAnnotation + "\n");
            sb.append("\tpublic ").append(oriClassStr + CLASS_SUFFIX_VIEWBEAN).append(" wrap(").append(oriClassStr + CLASS_SUFFIX_VIEWBEAN).append(" source){\n");
            sb.append("\t\tif(source == null){\n");
            sb.append("\t\t\treturn null;\n");
            sb.append("\t\t}\n");
            List<CommonTypeCouple> commonTypeCouples = getCommonTypeCouples();
            for (CommonTypeCouple commonTypeCouple : commonTypeCouples) {
                sb.append("\t\tsource.set" + firstUpper(commonTypeCouple.getProperty()) + "Desc(" + oriClassStr + "." + commonTypeCouple.getProperty() + "Map.get(source.get" + firstUpper(commonTypeCouple.getProperty() + "()));\n"));
            }
            sb.append("\t\treturn source;\n");
            sb.append("\t}\n");


            sb.append("\n}");
            File f = new File(MainFrame.config.get(Constant.SRC_ROOT_PATH));
            f = new File(f, packageStr.replace('.', File.separatorChar));
            if (!f.exists())
                f.mkdirs();
            f = new File(f, classStr + ".java");
            try {
                PrintWriter fw = new PrintWriter(f, MainFrame.config.get(Constant.ENCODE));
                fw.append(sb.toString());
                fw.close();

            } catch (IOException e1) {

                e1.printStackTrace();
                throw e1;
            }
        }


    }

    /*
     * 生成mapper 接口
     * */
    private void generateMapperFile(ActionEvent e, MainFrame frame) throws Throwable {

        if (jtfClass.getText().equals("")) {
            JOptionPane.showMessageDialog(frame, resourceBuddle.getString("InputClassName"));
            jtfClass.requestFocus();
        } else if (model.getRowCount() == 0) {
            JOptionPane.showMessageDialog(frame, resourceBuddle.getString("NoData"));
        }
//        else if(jtfPackage.getText().equals(""))
//        {
//            JOptionPane.showMessageDialog(frame, "输入包名");
//            jtfPackage.requestFocus();
//        }
        else {
            StringBuilder sb = new StringBuilder();
            String classStr = jtfClass.getText();
            if (classStr.endsWith(".java")) {
                classStr = classStr.substring(0, classStr.indexOf(".java"));
            }

            //class名中不能包含包名
            if (classStr.indexOf('.') >= 0) {
                JOptionPane.showMessageDialog(frame, "类名中不能包含包名!");
                jtfClass.requestFocus();
                return;
            }

            //String packageStr = jtfPackage.getText();
            String packageStr = MainFrame.config.get(Constant.MAPPER_PACKAGE);

            //action的包名需要加上servlet;
            String oriPackageStr = packageStr;
            //packageStr+="."+PACKAGE_PREFIX_MAPPER;

            //需要通过最初的classname来拼接其他类型的类的名称
            String oriClassStr = classStr;
            //类名需要加上Action后缀
            classStr += CLASS_SUFFIX_MAPPER;

            //获取原来文件中需要保留的信息
            //获取原来文件中需要保留的信息
            String filePath = MainFrame.config.get(Constant.SRC_ROOT_PATH);
            filePath += File.separator + packageStr.replace('.', File.separatorChar) + File.separator + classStr + ".java";
            Map<String, List<String>> savedMap = JavaSourceParserUtil.getNotAutoCode(filePath);
            List<String> savedImports = savedMap.get("import");
            if (savedImports == null) {
                savedImports = new ArrayList<String>();
            }

            List<String> savedFields = savedMap.get("field");
            if (savedFields == null) {
                savedFields = new ArrayList<String>();
            }

            List<String> savedMethods = savedMap.get("method");
            if (savedMethods == null) {
                savedMethods = new ArrayList<String>();
            }


            sb.append("package ").append(packageStr).append(";\n");
            
            
            
            /*
             * 导入相关的类
             * */
            sb.append("import java.util.List;\n");
            sb.append("import org.apache.ibatis.annotations.Param;\n");
            sb.append("import " + autoCodeReference + ";\n");

            sb.append("import " + MainFrame.config.get(Constant.BEAN_PACKAGE) + "." + oriClassStr + CLASS_SUFFIX_BEAN + ";\n");
            sb.append("import " + MainFrame.config.get(Constant.SEARCH_BEAN_PACKAGE) + "." + oriClassStr + CLASS_SUFFIX_SEARCHBEAN + ";\n");
            sb.append("import " + MainFrame.config.get(Constant.VIEW_BEAN_PACKAGE) + "." + oriClassStr + CLASS_SUFFIX_VIEWBEAN + ";\n");
            for (String str : savedImports) {
                sb.append(str);
            }


            //找出主键,只能有一个主键
            String keyProperty = null;
            int keyPropertyCount = 0;
            String keyPreopertyType = null;
            for (int i = 0; i < model.getRowCount(); i++) {
                //判断第5个字段的值是否为Y
                if (model.getValueAt(i, COL_INDEX_IS_PRIMARY_KEY).equals("Y")) {
                    keyProperty = model.getValueAt(i, COL_INDEX_PROPERTY_NAME).toString();
                    keyPropertyCount++;
                    keyPreopertyType = model.getValueAt(i, COL_INDEX_TYPE).toString();
                }
            }

            //主键数量多余一个，报错
            if (keyPropertyCount > 1) {
                JOptionPane.showMessageDialog(frame, "主键数量不能多余一个!");
                return;
            }

            sb.append("public interface ").append(classStr).append("\n{\n");

            for (String str : savedFields) {
                sb.append("\t" + str);
            }

            for (String str : savedMethods) {
                sb.append("\t" + str);
            }
            //定义add 接口
            sb.append("\t" + autoCodeAnnotation + "\n");
            sb.append("\t\tpublic Integer add").append(oriClassStr).append("(" + oriClassStr + CLASS_SUFFIX_BEAN + " bean);\n");

            //定义addSelective接口
            sb.append("\t" + autoCodeAnnotation + "\n");
            sb.append("\t\tpublic Integer add").append(oriClassStr).append("Selective").append("(" + oriClassStr + CLASS_SUFFIX_BEAN + " bean);\n");


            //定义del接口
            if (keyProperty != null) {
                sb.append("\t" + autoCodeAnnotation + "\n");
                sb.append("\t\tpublic Integer del").append(oriClassStr).append("(@Param(\"" + keyProperty + "\")" + keyPreopertyType + " " + convertColNameToHumpStyle(keyProperty) + ");\n");
            }

            //定义delWithClause接口
            sb.append("\t" + autoCodeAnnotation + "\n");
            sb.append("\t\tpublic Integer del").append(oriClassStr).append("WithClause").append("( @Param(value = \"search\")" + oriClassStr + CLASS_SUFFIX_SEARCHBEAN + " searchBean);\n");

            if (keyProperty != null) {
                //定义update接口
                sb.append("\t" + autoCodeAnnotation + "\n");
                sb.append("\t\tpublic Integer update").append(oriClassStr).append("(" + oriClassStr + CLASS_SUFFIX_BEAN + " bean);\n");
            }


            //定义updateSelective接口
            if (keyProperty != null) {
                sb.append("\t" + autoCodeAnnotation + "\n");
                sb.append("\t\tpublic Integer update").append(oriClassStr).append("Selective").append("(" + oriClassStr + CLASS_SUFFIX_BEAN + " bean);\n");
                sb.append("\t" + autoCodeAnnotation + "\n");
                sb.append("\t\tpublic Integer increaseUpdate").append(oriClassStr).append("Selective").append("(" + oriClassStr + CLASS_SUFFIX_BEAN + " bean);\n");
            }

            //定义updateSelectiveWithClause
            sb.append("\t" + autoCodeAnnotation + "\n");
            sb.append("\t\tpublic Integer update").append(oriClassStr).append("SelectiveWithClause").append("( @Param(value = \"bean\")  " + oriClassStr + CLASS_SUFFIX_BEAN + " bean,@Param(value = \"search\")" + oriClassStr + CLASS_SUFFIX_SEARCHBEAN + " searchBean);\n");

            sb.append("\t" + autoCodeAnnotation + "\n");
            sb.append("\t\tpublic Integer increaseUpdate").append(oriClassStr).append("SelectiveWithClause").append("( @Param(value = \"bean\")  " + oriClassStr + CLASS_SUFFIX_BEAN + " bean,@Param(value = \"search\")" + oriClassStr + CLASS_SUFFIX_SEARCHBEAN + " searchBean);\n");


            //定义list接口
            sb.append("\t" + autoCodeAnnotation + "\n");
            sb.append("\t\tpublic List<" + oriClassStr + CLASS_SUFFIX_VIEWBEAN + "> list").append("(" + oriClassStr + CLASS_SUFFIX_SEARCHBEAN + " bean);\n");
            //定义list count接口
            sb.append("\t" + autoCodeAnnotation + "\n");
            sb.append("\t\tpublic Integer listCount").append("(" + oriClassStr + CLASS_SUFFIX_SEARCHBEAN + " bean);\n");
            //定义getby主键接口
            if (keyProperty != null) {
                sb.append("\t" + autoCodeAnnotation + "\n");
                sb.append("\t\tpublic ").append(oriClassStr + CLASS_SUFFIX_VIEWBEAN).append(" getBy").append(convertColNameToHumpStyleWithFirstUpper(keyProperty)).append("(@Param(\"" + keyProperty + "\")" + keyPreopertyType + " " + convertColNameToHumpStyle(keyProperty) + ");\n");
            }


            sb.append("\n}");
            File f = new File(MainFrame.config.get(Constant.SRC_ROOT_PATH));
            f = new File(f, packageStr.replace('.', File.separatorChar));
            if (!f.exists())
                f.mkdirs();
            f = new File(f, classStr + ".java");
            try {
                PrintWriter fw = new PrintWriter(f, MainFrame.config.get(Constant.ENCODE));
                fw.append(sb.toString());
                fw.close();

            } catch (IOException e1) {

                e1.printStackTrace();
                throw e1;
            }
        }


    }

    public static String convertColNameToHumpStyleWithFirstUpper(String colName) {
        String ret = convertColNameToHumpStyle(colName);
        StringBuilder sbBuilder = new StringBuilder();
        if (ret != null && ret.length() > 0) {

            char ch = ret.charAt(0);
            if (ch >= 97 && ch <= 122) {

                ch -= 32;
                sbBuilder.append(ch);

            } else {
                sbBuilder.append(ch);

            }
            if (ret.length() > 1) {
                sbBuilder.append(ret.substring(1));
            }

        }
        return sbBuilder.toString();
    }

    public static String convertColNameToHumpStyle(String colName) {
        //将数据库以_分隔的字符串转换成驼峰风格的字符串
        if (colName == null) {
            return null;
        }

        String retString = new String(colName);

        StringBuilder sb = new StringBuilder();
        //找到每一个_,将后面跟着的第一个字母大写，并去掉_
        for (int i = 0; i < retString.length(); i++) {
            char ch = retString.charAt(i);
            //如果是_
            if (ch == '_') {
                //查看是否已经是最后一个字符
                if (i == retString.length() - 1) {

                } else {
                    //将后面跟着的字符转成大写之后，添加到sb中
                    char source = retString.charAt(i + 1);
                    if (source >= 97 && source <= 122) {
                        source -= 32;
                    }

                    sb.append(source);
                    i += 1;
                }
            } else {
                sb.append(ch);
            }
        }
        String ret = sb.toString();
        return ret;

    }

    /*
     * 生成mybatis xml文件
     * */
    private void generateMybatisFile(ActionEvent e, MainFrame frame) throws Throwable {
        if (jtfClass.getText().equals("")) {
            JOptionPane.showMessageDialog(frame, resourceBuddle.getString("InputClassName"));
            jtfClass.requestFocus();
        } else if (model.getRowCount() == 0) {
            JOptionPane.showMessageDialog(frame, resourceBuddle.getString("NoData"));
        }
//        else if(jtfPackage.getText().equals(""))
//        {
//            JOptionPane.showMessageDialog(frame, "输入包名");
//            jtfPackage.requestFocus();
//        }
        else {
            StringBuilder sb = new StringBuilder();
            String classStr = jtfClass.getText();
            if (classStr.endsWith(".java")) {
                classStr = classStr.substring(0, classStr.indexOf(".java"));
            }

            //class名中不能包含包名
            if (classStr.indexOf('.') >= 0) {
                JOptionPane.showMessageDialog(frame, "类名中不能包含包名!");
                jtfClass.requestFocus();
                return;
            }


            //找出主键,只能有一个主键
            String keyProperty = null;
            String keyColumn = null;
            int keyPropertyCount = 0;
            String keyPreopertyType = null;
            for (int i = 0; i < model.getRowCount(); i++) {
                //判断第6个字段的值是否为Y
                if (model.getValueAt(i, COL_INDEX_IS_PRIMARY_KEY).equals("Y")) {
                    keyColumn = model.getValueAt(i, COL_INDEX_COLUMN_NAME).toString();
                    keyProperty = model.getValueAt(i, COL_INDEX_PROPERTY_NAME).toString();
                    keyPropertyCount++;
                    keyPreopertyType = model.getValueAt(i, COL_INDEX_TYPE).toString();
                }
            }

            //主键数量多余一个，报错
            if (keyPropertyCount > 1) {
                JOptionPane.showMessageDialog(frame, "主键数量不能多余一个!");
                return;
            }


            //找出自增字段

            //找出主键,只能有一个主键
            String ascProperty = null;
            int ascPropertyCount = 0;
            String ascColumn = null;
            String ascPreopertyType = null;
            for (int i = 0; i < model.getRowCount(); i++) {
                //判断第7个字段的值是否为Y
                if (model.getValueAt(i, COL_INDEX_IS_AUTO_INCREASEMENT).equals("Y")) {
                    ascColumn = model.getValueAt(i, COL_INDEX_COLUMN_NAME).toString();
                    ascProperty = model.getValueAt(i, COL_INDEX_PROPERTY_NAME).toString();
                    ascPropertyCount++;
                    ascPreopertyType = model.getValueAt(i, COL_INDEX_TYPE).toString();
                }
            }

            //主键数量多余一个，报错
            if (ascPropertyCount > 1) {
                JOptionPane.showMessageDialog(frame, "主键数量不能多余一个!");
                return;
            }


            String oriClassStr = classStr;
            //查询是否文件已经存在，如果文件已经存在，则将已经存在的文档读入内存，并构建document
            String filePath = MainFrame.config.get(Constant.XML_FILE_PATH) + File.separator + oriClassStr + "-SqlMapper.xml";
            Map<String, List<Element>> savedElementMap = handleExistXmlFile(filePath);


//            String packageStr = jtfPackage.getText();
            String beanPackage = MainFrame.config.get(Constant.BEAN_PACKAGE);
            String viewBeanPackage = MainFrame.config.get(Constant.VIEW_BEAN_PACKAGE);
            String searchBeanPackage = MainFrame.config.get(Constant.SEARCH_BEAN_PACKAGE);
            String mapperPackage = MainFrame.config.get(Constant.MAPPER_PACKAGE);


            //String oriPackageStr = packageStr;


            //使用freemaker模板生成文件
            try {
                Configuration cfg = new Configuration();
                cfg.setClassForTemplateLoading(this.getClass(), "template");
                cfg.setObjectWrapper(new DefaultObjectWrapper());
                cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
                Map root = new HashMap();

                //root.put("oriPackageName", oriPackageStr);

                root.put("beanPackage", beanPackage);
                root.put("viewBeanPackage", viewBeanPackage);
                root.put("searchBeanPackage", searchBeanPackage);
                root.put("mapperPackage", mapperPackage);

                root.put("foreignKeys", selectedForeignKeys);

//            root.put("packagePrefixMapper", PACKAGE_PREFIX_MAPPER);
//            root.put("packagePrefixBean", PACKAGE_PREFIX_BEAN);
//            root.put("packagePrefixSearchBean", PACKAGE_PREFIX_SEARCHBEAN);
//            root.put("packagePrefixViewBean", PACKAGE_PREFIX_VIEWBEAN);

                root.put("oriClassName", oriClassStr);

                root.put("classSuffixMapper", CLASS_SUFFIX_MAPPER);
                root.put("classSuffixBean", CLASS_SUFFIX_BEAN);
                root.put("classSuffixSearchBean", CLASS_SUFFIX_SEARCHBEAN);
                root.put("classSuffixViewBean", CLASS_SUFFIX_VIEWBEAN);

                //表名
                root.put("tableName", this.tableName);

                //列名

                //获取所有的列名
                List<String> colNames = new ArrayList<String>();
                List<String> propertyNames = new ArrayList<>();
                List<String> colNamesWithoutAscProperty = new ArrayList<String>();
                List<String> propertyNamesWithoutAscProperty = new ArrayList<>();
                List<String> colNameWithoutKeyProperty = new ArrayList<String>();
                List<String> propertyNamesWithoutKeyProperty = new ArrayList<>();

                //除去自增和主键之外的属性集合，用于生成resultMAP

                List<ColumnPropertyCouple> normalColumnPropertyCouples = new ArrayList<>();

                //全体列和属性对的合集
                List<ColumnPropertyCouple> columnPropertyCouples = new ArrayList<>();

                for (int i = 0; i < model.getRowCount(); i++) {
                    ColumnPropertyCouple columnPropertyCouple = new ColumnPropertyCouple();
                    columnPropertyCouple.setColumn(model.getValueAt(i, COL_INDEX_COLUMN_NAME).toString());
                    columnPropertyCouple.setProperty(model.getValueAt(i, COL_INDEX_PROPERTY_NAME).toString());
                    columnPropertyCouples.add(columnPropertyCouple);
                    if ((!model.getValueAt(i, COL_INDEX_COLUMN_NAME).equals(ascColumn)) && (!model.getValueAt(i, COL_INDEX_COLUMN_NAME).equals(keyColumn))) {
                        normalColumnPropertyCouples.add(columnPropertyCouple);
                    }
                }
                for (int i = 0; i < model.getRowCount(); i++) {
                    colNames.add(model.getValueAt(i, COL_INDEX_COLUMN_NAME).toString());
                    propertyNames.add(model.getValueAt(i, COL_INDEX_PROPERTY_NAME).toString());
                    if (!model.getValueAt(i, COL_INDEX_PROPERTY_NAME).equals(ascProperty)) {
                        colNamesWithoutAscProperty.add(model.getValueAt(i, COL_INDEX_COLUMN_NAME).toString());
                        propertyNamesWithoutAscProperty.add(model.getValueAt(i, COL_INDEX_PROPERTY_NAME).toString());
                    }

                    if (!model.getValueAt(i, COL_INDEX_PROPERTY_NAME).equals(keyProperty)) {
                        colNameWithoutKeyProperty.add(model.getValueAt(i, COL_INDEX_COLUMN_NAME).toString());
                        propertyNamesWithoutKeyProperty.add(model.getValueAt(i, COL_INDEX_PROPERTY_NAME).toString());
                    }

                }

                //全部的列名
                root.put("colNames", colNames);
                root.put("propertyNames", propertyNames);

                root.put("colNamesWithoutKeyProperty", colNameWithoutKeyProperty);
                root.put("propertyNamesWithoutKeyProperty", propertyNamesWithoutKeyProperty);

                root.put("colNamesWithoutAscProperty", colNamesWithoutAscProperty);
                root.put("propertyNamesWithoutAscProperty", propertyNamesWithoutAscProperty);

                root.put("normalColumnPropertyCouples", normalColumnPropertyCouples);

                root.put("columnPropertyCouples", columnPropertyCouples);


                //主键列
                root.put("keyProperty", keyProperty);
                root.put("keyColumn", keyColumn);

                root.put("keyPropertyType", keyPreopertyType);
                root.put("keyPropertyInHumpStyle", convertColNameToHumpStyle(keyProperty));
                root.put("keyPropertyInHumpStyleWithFirstUpper", convertColNameToHumpStyleWithFirstUpper(keyProperty));

                //自增列
                root.put("ascProperty", ascProperty);
                root.put("ascColumn", ascColumn);

                root.put("ascPreopertyType", ascPreopertyType);
                root.put("ascPropertyInHumpStyle", convertColNameToHumpStyle(ascProperty));
                root.put("ascPropertyInHumpStyleWithFirstUpper", convertColNameToHumpStyleWithFirstUpper(ascProperty));


                //主表的别名
                root.put("primaryTableAliasOne", primaryTableAliasOne.getText());
                root.put("primaryTableAliasTwo", primaryTableAliasTwo.getText());

                //外键的列名
                root.put("foreignKeys", selectedForeignKeys);


                Template template = cfg.getTemplate("mybatis.ftl");


                File f = new File(MainFrame.config.get(Constant.XML_FILE_PATH));
                //f = new File(f,"mybatis");
                if (!f.exists())
                    f.mkdirs();
                f = new File(f, oriClassStr + "-SqlMapper.xml");

                PrintWriter fw = new PrintWriter(f, MainFrame.config.get(Constant.ENCODE));
                template.process(root, fw);
                fw.close();


                //重新使用jdom读入新生成的文档，并与旧的文档进行合并

                handleNewXmlFile(filePath, savedElementMap);


            } catch (Throwable t) {

                t.printStackTrace();
                throw t;
            }


        }
    }


    private void handleNewXmlFile(String filePath, Map<String, List<Element>> map) {

        try {
            File f = new File(filePath);
            SAXBuilder builder = new SAXBuilder();
            FileInputStream fileInputStream = new FileInputStream(f);

            Document document = builder.build(fileInputStream);//获得文档对象
            fileInputStream.close();

            //root节点为mapper
            Element mapperElement = document.getRootElement();

            List<Element> resultRetElements = map.get("customResult");
            if (resultRetElements != null && resultRetElements.size() > 0) {
                //找到resultMap
                List<Element> resultMapElements = mapperElement.getChildren("resultMap");
                for (Element resultMapElement : resultMapElements) {
                    Attribute idAttr = resultMapElement.getAttribute("id");
                    if (idAttr != null && "baseResultMap".equals(idAttr.getValue())) {
                        for (Element element : resultRetElements) {
                            resultMapElement.addContent(element.detach());
                        }
                    }
                }
            }

            List<Element> resultMapRetElements = map.get("customResultMap");
            if (resultMapRetElements != null && resultMapRetElements.size() > 0) {
                for (Element element : resultMapRetElements) {
                    mapperElement.addContent(0, element.detach());
                }
            }

            List<Element> statementRetElements = map.get("customStatement");
            if (statementRetElements != null && statementRetElements.size() > 0) {
                for (Element element : statementRetElements) {
                    mapperElement.addContent(element.detach());
                }
            }

            Format format = Format.getCompactFormat();
            format.setEncoding("utf-8");
            //这行保证输出后的xml的格式
            format.setIndent(" ");
            XMLOutputter xmlout = new XMLOutputter(format);
            ByteArrayOutputStream byteRsp = new ByteArrayOutputStream();
            xmlout.output(document, byteRsp);

            //写入到文件中
            PrintWriter fw = new PrintWriter(f, MainFrame.config.get(Constant.ENCODE));
            fw.append(byteRsp.toString("utf-8"));
            fw.close();


        } catch (Throwable t) {
            throw new RuntimeException(t);
        }

    }


    private Map<String, List<Element>> handleExistXmlFile(String filePath) {
        try {
            File f = new File(filePath);
            Map<String, List<Element>> map = new HashMap<>();


            List<Element> statementRetElements = new ArrayList<Element>();
            List<Element> resultRetElements = new ArrayList<Element>();
            List<Element> resultMapRetElements = new ArrayList<Element>();

            map.put("customStatement", statementRetElements);
            map.put("customResult", resultRetElements);
            map.put("customResultMap", resultMapRetElements);

            if (!"Y".equals(MainFrame.config.get(Constant.CODE_SAVE_FLAG))) {
                return map;
            }

            if (!f.exists()) {

                return map;
            } else {
                SAXBuilder builder = new SAXBuilder();

                FileInputStream fileInputStream = new FileInputStream(f);

                Document document = builder.build(fileInputStream);//获得文档对象
                fileInputStream.close();

                //root节点为mapper
                Element mapperElement = document.getRootElement();
                if (mapperElement != null) {


                    //获取所有的直接子节点
                    List<Element> mapperChildrenElements = mapperElement.getChildren();

                    for (Element mapperChildren : mapperChildrenElements) {
                        //如果是resultMap节点
                        if ("resultMap".equals(mapperChildren.getName())) {
                            Element resultMapElement = mapperChildren;
                            //判断id是否是baseResultMap,如果不是，则是自定义的map
                            Attribute idAttr = resultMapElement.getAttribute("id");
                            if (idAttr != null && "baseResultMap".equals(idAttr.getValue())) {
                                //查看是否有自定义的result
                                List<Element> resultElements = resultMapElement.getChildren("result");
                                //对于没有设置autocode属性的，都是为自定义的result，需要保留
                                for (Element resultElement : resultElements) {
                                    Attribute autocodeAttr = resultElement.getAttribute("autocode");
                                    if (autocodeAttr != null && "true".equals(autocodeAttr.getValue())) {

                                    } else {
                                        resultRetElements.add(resultElement);

                                    }
                                }

                            }

                            //自定义的resultmap需要保留
                            else {
                                resultMapRetElements.add(resultMapElement);
                            }

                        } else if ("insert".equals(mapperChildren.getName())
                                || "delete".equals(mapperChildren.getName())
                                || "update".equals(mapperChildren.getName())
                                || "select".equals(mapperChildren.getName())) {

                            //判断是否有autocode属性
                            Attribute autocodeAttr = mapperChildren.getAttribute("autocode");
                            if (!(autocodeAttr != null && "true".equals(autocodeAttr.getValue()))) {
                                statementRetElements.add(mapperChildren);
                            }


                        }


                    }


                }
                return map;


            }
        } catch (Throwable t) {
            throw new RuntimeException(t);
        }


    }

    private boolean isIncludeTimestamp() {
        //便利所有的列，查看是否包含timestamp类型
        for (int i = 0; i < model.getRowCount(); i++) {
            if ("Timestamp".equals(model.getValueAt(i, 1))) {
                return true;
            }
        }
        return false;
    }

    private boolean isIncludeDecimal() {
        //便利所有的列，查看是否包含timestamp类型
        for (int i = 0; i < model.getRowCount(); i++) {
            if ("BigDecimal".equals(model.getValueAt(i, 1))) {
                return true;
            }
        }
        return false;
    }

    /*
     * 生成search bean
     * */
    private void generateSearchBean(ActionEvent e, MainFrame frame) throws Throwable {
        if (jtfClass.getText().equals("")) {
            JOptionPane.showMessageDialog(frame, resourceBuddle.getString("InputClassName"));
            jtfClass.requestFocus();
        } else if (model.getRowCount() == 0) {
            JOptionPane.showMessageDialog(frame, resourceBuddle.getString("NoData"));
        }
//        else if(jtfPackage.getText().equals(""))
//        {
//            JOptionPane.showMessageDialog(frame, "输入包名");
//            jtfPackage.requestFocus();
//        }
        else {
            StringBuilder sb = new StringBuilder();
            String classStr = jtfClass.getText();
            if (classStr.endsWith(".java")) {
                classStr = classStr.substring(0, classStr.indexOf(".java"));
            }

            //class名中不能包含包名
            if (classStr.indexOf('.') >= 0) {
                JOptionPane.showMessageDialog(frame, "类名中不能包含包名!");
                jtfClass.requestFocus();
                return;
            }

            String oriClassStr = classStr;
            classStr += CLASS_SUFFIX_SEARCHBEAN;

            //String packageStr = jtfPackage.getText();
            String packageStr = MainFrame.config.get(Constant.SEARCH_BEAN_PACKAGE);
            String oriPackageStr = packageStr;
            //packageStr+="."+PACKAGE_PREFIX_SEARCHBEAN;
//            if(classStr.indexOf('.')!=-1)
//            {
//                if(classStr.indexOf('.')!=-1)
//                {
//                    packageStr = classStr.substring(0,classStr.lastIndexOf('.'));
//                    classStr = classStr.substring(classStr.lastIndexOf('.')+1);
//                }
//            }

            //获取原来文件中需要保留的信息
            String filePath = MainFrame.config.get(Constant.SRC_ROOT_PATH);
            filePath += File.separator + packageStr.replace('.', File.separatorChar) + File.separator + classStr + ".java";
            Map<String, List<String>> savedMap = JavaSourceParserUtil.getNotAutoCode(filePath);
            List<String> savedImports = savedMap.get("import");
            if (savedImports == null) {
                savedImports = new ArrayList<String>();
            }

            List<String> savedFields = savedMap.get("field");
            if (savedFields == null) {
                savedFields = new ArrayList<String>();
            }

            List<String> savedMethods = savedMap.get("method");
            if (savedMethods == null) {
                savedMethods = new ArrayList<String>();
            }

            sb.append("package ").append(packageStr).append(";\n");
            //导入类
            if (isIncludeTimestamp()) {
                sb.append("import java.sql.Timestamp;\n");
            }
            if (isIncludeDecimal()) {
                sb.append("import java.math.BigDecimal;\n");
            }
            sb.append("import " + autoCodeReference + ";\n");

            sb.append("import " + MainFrame.config.get(Constant.BASE_SEARCH_BEAN) + ";\n");
            sb.append("import java.util.List;\n");
            sb.append("import java.util.ArrayList;\n");
            sb.append("import java.util.Map;\n");
            sb.append("import java.util.LinkedHashMap;\n");

            for (String str : savedImports) {
                sb.append(str);
            }

            sb.append("public class ").append(classStr).append(" extends BaseSearchBean").append("\n{\n");

            //定义用于收集order by的map
            sb.append("\tprivate Map<String,String>orderMap = new LinkedHashMap<>();\n");

            ArrayList<String> listVar = new ArrayList<>();
            ArrayList<String> listMethod = new ArrayList<>();
            ArrayList<String> listCommon = new ArrayList<>();
            int count = model.getRowCount();
            /**
             *
             */
            for (int i = 0; i < count; i++) {
                if (!model.getValueAt(i, COL_INDEX_PROPERTY_NAME).toString().equals(""))//如果有输入变量名
                {
                    //属性名称
                    String propertyName = model.getValueAt(i, COL_INDEX_PROPERTY_NAME).toString();
                    String columnName = model.getValueAt(i, COL_INDEX_COLUMN_NAME).toString();
                    String common = "";
                    if (!model.getValueAt(i, COL_INDEX_REMARK).equals(""))
                        common = "\t/**\n\t * " + model.getValueAt(i, COL_INDEX_REMARK).toString() + "\n\t */\n";
                    listCommon.add(common);
                    StringBuilder sb2 = new StringBuilder();
                    sb2.append("\t" + autoCodeAnnotation + "\n");
                    sb2.append("\t");
                    if (!model.getValueAt(i, COL_INDEX_DECORATOR).equals("")) {
                        sb2.append(model.getValueAt(i, COL_INDEX_DECORATOR).toString() + " ");
                    }
                    sb2.append(model.getValueAt(i, COL_INDEX_TYPE).toString() + " ");
                    sb2.append(model.getValueAt(i, COL_INDEX_PROPERTY_NAME).toString() + ";\n");
                    listVar.add(sb2.toString());
                    sb2 = new StringBuilder();
                    sb2.append("\t/**\n\t*设置" + model.getValueAt(i, COL_INDEX_REMARK).toString() + "\n\t*/\n");
                    sb2.append("\t" + autoCodeAnnotation + "\n");
                    sb2.append("\tpublic " + classStr + " set").append(firstUpper(model.getValueAt(i, COL_INDEX_PROPERTY_NAME).toString())).append("(").
                            append(model.getValueAt(i, COL_INDEX_TYPE)).append(" ").append(model.getValueAt(i, COL_INDEX_PROPERTY_NAME))
                            .append(")\n\t{\n");
                    sb2.append("\t\tthis.").append(model.getValueAt(i, COL_INDEX_PROPERTY_NAME)).append(" = ").append(model.getValueAt(i, COL_INDEX_PROPERTY_NAME)).append(";\n");
                    sb2.append("\t\treturn this;\n");
                    sb2.append("\t}\n");
                    sb2.append("\t/**\n\t*获取" + model.getValueAt(i, COL_INDEX_REMARK).toString() + "\n\t*/\n");
                    sb2.append("\t" + autoCodeAnnotation + "\n");
                    sb2.append("\tpublic " + model.getValueAt(i, COL_INDEX_TYPE).toString() + " get").append(firstUpper(model.getValueAt(i, COL_INDEX_PROPERTY_NAME).toString())).append("()\n\t{\n");
                    sb2.append("\t\treturn ").append(model.getValueAt(i, COL_INDEX_PROPERTY_NAME)).append(";\n");
                    sb2.append("\t}\n");
                    listMethod.add(sb2.toString());

                    //增加两个变量，代表开始和结束
                    //变量名
                    sb2 = new StringBuilder();
                    String startVarName = model.getValueAt(i, COL_INDEX_PROPERTY_NAME).toString() + SEARCH_START_SUFFIX;

                    String startVarComment = "";
                    listCommon.add(startVarComment);
                    sb2.append("\t" + autoCodeAnnotation + "\n");
                    sb2.append("\t");
                    //定义开始变量
                    if (!model.getValueAt(i, COL_INDEX_DECORATOR).equals("")) {
                        sb2.append(model.getValueAt(i, COL_INDEX_DECORATOR).toString() + " ");
                    }
                    sb2.append(model.getValueAt(i, COL_INDEX_TYPE).toString() + " ");
                    sb2.append(startVarName + ";\n");
                    listVar.add(sb2.toString());
                    //定义开始变量的getter和setter
                    sb2 = new StringBuilder();
                    sb2.append("\t/**\n\t*设置期间查询的开始条件\n\t*/\n");
                    sb2.append("\t" + autoCodeAnnotation + "\n");
                    sb2.append("\tpublic " + classStr + " set").append(firstUpper(startVarName)).append("(").
                            append(model.getValueAt(i, COL_INDEX_TYPE)).append(" ").append(startVarName)
                            .append(")\n\t{\n");
                    sb2.append("\t\tthis.").append(startVarName).append(" = ").append(startVarName).append(";\n");
                    sb2.append("\t\treturn this;\n");
                    sb2.append("\t}\n");
                    sb2.append("\t/**\n\t*获取期间查询开始条件\n\t*/\n");
                    sb2.append("\t" + autoCodeAnnotation + "\n");
                    sb2.append("\tpublic " + model.getValueAt(i, COL_INDEX_TYPE).toString() + " get").append(firstUpper(startVarName)).append("()\n\t{\n");
                    sb2.append("\t\treturn ").append(startVarName).append(";\n");
                    sb2.append("\t}\n");
                    listMethod.add(sb2.toString());


                    sb2 = new StringBuilder();
                    String endVarName = model.getValueAt(i, COL_INDEX_PROPERTY_NAME).toString() + SEARCH_END_SUFFIX;

                    String endVarComment = "";
                    listCommon.add(endVarComment);
                    sb2.append("\t" + autoCodeAnnotation + "\n");
                    sb2.append("\t");
                    //定义结束变量
                    if (!model.getValueAt(i, COL_INDEX_DECORATOR).equals("")) {
                        sb2.append(model.getValueAt(i, COL_INDEX_DECORATOR).toString() + " ");
                    }
                    sb2.append(model.getValueAt(i, COL_INDEX_TYPE).toString() + " ");
                    sb2.append(endVarName + ";\n");
                    listVar.add(sb2.toString());
                    //定义开始变量的getter和setter
                    sb2 = new StringBuilder();
                    sb2.append("\t/**\n\t*设置期间查询的结束条件\n\t*/\n");
                    sb2.append("\t" + autoCodeAnnotation + "\n");
                    sb2.append("\tpublic " + classStr + " set").append(firstUpper(endVarName)).append("(").
                            append(model.getValueAt(i, COL_INDEX_TYPE)).append(" ").append(endVarName)
                            .append(")\n\t{\n");
                    sb2.append("\t\tthis.").append(endVarName).append(" = ").append(endVarName).append(";\n");
                    sb2.append("\t\treturn this;\n");
                    sb2.append("\t}\n");
                    sb2.append("\t/**\n\t*获取期间查询开始条件\n\t*/\n");
                    sb2.append("\t" + autoCodeAnnotation + "\n");
                    sb2.append("\tpublic " + model.getValueAt(i, COL_INDEX_TYPE).toString() + " get").append(firstUpper(endVarName)).append("()\n\t{\n");
                    sb2.append("\t\treturn ").append(endVarName).append(";\n");
                    sb2.append("\t}\n");
                    listMethod.add(sb2.toString());

                    //生成变量的集合列表
                    sb2 = new StringBuilder();
                    String listVarName = model.getValueAt(i, COL_INDEX_PROPERTY_NAME).toString() + SEARCH_LIST_SUFFIX;

                    String listVarComment = "";
                    listCommon.add(listVarComment);
                    sb2.append("\t" + autoCodeAnnotation + "\n");
                    sb2.append("\t");
                    //定义结束变量
                    if (!model.getValueAt(i, COL_INDEX_DECORATOR).equals("")) {
                        sb2.append(model.getValueAt(i, COL_INDEX_DECORATOR).toString() + " ");
                    }
                    sb2.append("List<" + model.getValueAt(i, COL_INDEX_TYPE).toString() + "> ");
                    sb2.append(listVarName + " = new ArrayList<" + model.getValueAt(i, COL_INDEX_TYPE) + ">();\n");
                    listVar.add(sb2.toString());
                    //定义开始变量的getter和setter
                    sb2 = new StringBuilder();
                    sb2.append("\t/**\n\t*设置集合查询条件\n\t*/\n");
                    sb2.append("\t" + autoCodeAnnotation + "\n");
                    sb2.append("\tpublic " + classStr + " set").append(firstUpper(listVarName)).append("(List<").
                            append(model.getValueAt(i, COL_INDEX_TYPE)).append("> ").append(listVarName)
                            .append(")\n\t{\n");
                    sb2.append("\t\tthis.").append(listVarName).append(" = ").append(listVarName).append(";\n");
                    sb2.append("\t\treturn this;\n");
                    sb2.append("\t}\n");
                    sb2.append("\t/**\n\t*获取集合查询条件\n\t*/\n");
                    sb2.append("\t" + autoCodeAnnotation + "\n");
                    sb2.append("\tpublic List<" + model.getValueAt(i, COL_INDEX_TYPE).toString() + "> get").append(firstUpper(listVarName)).append("()\n\t{\n");
                    sb2.append("\t\treturn ").append(listVarName).append(";\n");
                    sb2.append("\t}\n");
                    listMethod.add(sb2.toString());


                    //定义orderby desc的方法

                    sb2 = new StringBuilder();
                    sb2.append("\t/**\n\t*设置按" + propertyName + "降序查询\n\t*/\n");
                    sb2.append("\t" + autoCodeAnnotation + "\n");
                    sb2.append("\tpublic " + classStr + " orderBy").append(firstUpper(propertyName)).append("Desc(").append(")\n\t{\n");
                    sb2.append("\t\torderMap.put(\"").append(columnName).append("\",\"desc\");\n");
                    sb2.append("\t\treturn this;\n");
                    sb2.append("\t}\n");
                    listMethod.add(sb2.toString());

                    //定义orderby asc的方法

                    sb2 = new StringBuilder();
                    sb2.append("\t/**\n\t*设置按" + propertyName + "升序查询\n\t*/\n");
                    sb2.append("\t" + autoCodeAnnotation + "\n");
                    sb2.append("\tpublic " + classStr + " orderBy").append(firstUpper(propertyName)).append("Asc(").append(")\n\t{\n");
                    sb2.append("\t\torderMap.put(\"").append(columnName).append("\",\"asc\");\n");
                    sb2.append("\t\treturn this;\n");
                    sb2.append("\t}\n");
                    listMethod.add(sb2.toString());


                }
            }
            for (String str : savedFields) {
                sb.append("\t" + str);
            }

            for (String str : savedMethods) {
                sb.append("\t" + str);
            }

            for (int i = 0; i < listVar.size(); i++) {
                sb.append(listCommon.get(i));
                sb.append(listVar.get(i));
            }
            for (int i = 0; i < listMethod.size(); i++) {
                sb.append(listMethod.get(i));
            }
            sb.append("}");
            File f = new File(MainFrame.config.get(Constant.SRC_ROOT_PATH));
            f = new File(f, packageStr.replace('.', File.separatorChar));
            if (!f.exists())
                f.mkdirs();
            f = new File(f, classStr + ".java");
            try {
                PrintWriter fw = new PrintWriter(f, MainFrame.config.get(Constant.ENCODE));
                fw.append(sb.toString());
                fw.close();

            } catch (IOException e1) {

                e1.printStackTrace();
                throw e1;
            }
        }
    }


    /*
     * 生成view bean
     * */
    private void generateViewBean(ActionEvent e, MainFrame frame) throws Throwable {
        if (jtfClass.getText().equals("")) {
            JOptionPane.showMessageDialog(frame, resourceBuddle.getString("InputClassName"));
            jtfClass.requestFocus();
        } else if (model.getRowCount() == 0) {
            JOptionPane.showMessageDialog(frame, resourceBuddle.getString("NoData"));
        }
//        else if(jtfPackage.getText().equals(""))
//        {
//            JOptionPane.showMessageDialog(frame, "输入包名");
//            jtfPackage.requestFocus();
//        }
        else {
            StringBuilder sb = new StringBuilder();
            String classStr = jtfClass.getText();
            if (classStr.endsWith(".java")) {
                classStr = classStr.substring(0, classStr.indexOf(".java"));
            }

            //class名中不能包含包名
            if (classStr.indexOf('.') >= 0) {
                JOptionPane.showMessageDialog(frame, "类名中不能包含包名!");
                jtfClass.requestFocus();
                return;
            }

            //  String packageStr = jtfPackage.getText();
            String packageStr = MainFrame.config.get(Constant.VIEW_BEAN_PACKAGE);

            String beanPackage = MainFrame.config.get(Constant.BEAN_PACKAGE);


            //action的包名需要加上servlet;
            String oriPackageStr = packageStr;
            //packageStr+="."+PACKAGE_PREFIX_VIEWBEAN;

            //需要通过最初的classname来拼接其他类型的类的名称
            String oriClassStr = classStr;
            //类名需要加上Action后缀
            classStr += CLASS_SUFFIX_VIEWBEAN;

            //获取原来文件中需要保留的信息
            String filePath = MainFrame.config.get(Constant.SRC_ROOT_PATH);
            filePath += File.separator + packageStr.replace('.', File.separatorChar) + File.separator + classStr + ".java";
            Map<String, List<String>> savedMap = JavaSourceParserUtil.getNotAutoCode(filePath);
            List<String> savedImports = savedMap.get("import");
            if (savedImports == null) {
                savedImports = new ArrayList<String>();
            }

            List<String> savedFields = savedMap.get("field");
            if (savedFields == null) {
                savedFields = new ArrayList<String>();
            }

            List<String> savedMethods = savedMap.get("method");
            if (savedMethods == null) {
                savedMethods = new ArrayList<String>();
            }


            sb.append("package ").append(packageStr).append(";\n");
            
            
            /*
             * 导入相关的类
             * */

            sb.append("import " + beanPackage + "." + oriClassStr + CLASS_SUFFIX_BEAN + ";\n");
            sb.append("import " + autoCodeReference + ";\n");

            for (String str : savedImports) {
                sb.append(str);
            }


            sb.append("public class ").append(classStr).append(" extends ").append(oriClassStr + CLASS_SUFFIX_BEAN).append("\n{\n");

            //定义常量的名称字段
            List<CommonTypeCouple> commonTypeCouples = getCommonTypeCouples();
            for (CommonTypeCouple commonTypeCouple : commonTypeCouples) {
                sb.append("\t" + autoCodeAnnotation + "\n");
                sb.append("\tprivate String " + commonTypeCouple.getProperty() + "Desc;\n\n");
            }

            for (String str : savedFields) {
                sb.append("\t" + str);
            }

            //定义外键中的字段
            for (ForeignKey foreignKey : selectedForeignKeys) {
                for (Column column : foreignKey.getPkTable().getColumns()) {
                    sb.append("\t" + autoCodeAnnotation + "\n");
                    sb.append("\tprivate " + column.getType() + " " + column.getPropertyName() + ";\n\n");
                }
            }


            sb.append("\n");
            for (String str : savedMethods) {
                sb.append("\t" + str);
            }
            for (CommonTypeCouple commonTypeCouple : commonTypeCouples) {
                sb.append("\t" + autoCodeAnnotation + "\n");
                sb.append("\tpublic String get" + firstUpper(commonTypeCouple.getProperty() + "Desc(){\n"));
                sb.append("\t\treturn " + commonTypeCouple.getProperty() + "Desc;\n");
                sb.append("\t}\n");

                sb.append("\t" + autoCodeAnnotation + "\n");
                sb.append("\tpublic void set" + firstUpper(commonTypeCouple.getProperty()) + "Desc(String " + commonTypeCouple.getProperty() + "Desc){\n");
                sb.append("\t\tthis." + commonTypeCouple.getProperty() + "Desc = " + commonTypeCouple.getProperty() + "Desc;\n");
                sb.append("\t}\n");
            }

            for (ForeignKey foreignKey : selectedForeignKeys) {
                for (Column column : foreignKey.getPkTable().getColumns()) {
                    sb.append("\t" + autoCodeAnnotation + "\n");
                    sb.append("\tpublic " + column.getType() + " get" + firstUpper(column.getPropertyName() + "(){\n"));
                    sb.append("\t\treturn " + column.getPropertyName() + ";\n");
                    sb.append("\t}\n");

                    sb.append("\t" + autoCodeAnnotation + "\n");
                    sb.append("\tpublic void set" + firstUpper(column.getPropertyName()) + "(" + column.getType() + " " + column.getPropertyName() + "){\n");
                    sb.append("\t\tthis." + column.getPropertyName() + " = " + column.getPropertyName() + ";\n");
                    sb.append("\t}\n");
                }
            }


            sb.append("\n}");
            File f = new File(MainFrame.config.get(Constant.SRC_ROOT_PATH));
            f = new File(f, packageStr.replace('.', File.separatorChar));
            if (!f.exists())
                f.mkdirs();
            f = new File(f, classStr + ".java");
            try {
                PrintWriter fw = new PrintWriter(f, MainFrame.config.get(Constant.ENCODE));
                fw.append(sb.toString());
                fw.close();

            } catch (IOException e1) {

                e1.printStackTrace();
                throw e1;
            }
        }
    }

	/*
     *
	 * */
//	private void generateActionFile(ActionEvent e,MainFrame frame) throws Throwable
//	{
//	    if(jtfClass.getText().equals(""))
//        {
//            JOptionPane.showMessageDialog(frame, resourceBuddle.getString("InputClassName"));
//            jtfClass.requestFocus();
//        }else if(model.getRowCount()==0)
//        {
//            JOptionPane.showMessageDialog(frame, resourceBuddle.getString("NoData"));
//        }
//        else if(jtfPackage.getText().equals(""))
//        {
//            JOptionPane.showMessageDialog(frame, "输入包名");
//            jtfPackage.requestFocus();
//        }
//        else
//        {
//            StringBuilder sb = new StringBuilder();
//            String classStr = jtfClass.getText();
//            if(classStr.endsWith(".java"))
//            {
//                classStr = classStr.substring(0,classStr.indexOf(".java"));
//            }
//
//            //class名中不能包含包名
//            if(classStr.indexOf('.')>=0)
//            {
//                JOptionPane.showMessageDialog(frame, "类名中不能包含包名!");
//                jtfClass.requestFocus();
//                return;
//            }
//
//            String packageStr = jtfPackage.getText();
//
//
//            //action的包名需要加上servlet;
//            String oriPackageStr = packageStr;
//            packageStr+="."+PACKAGE_PREFIX_ACTION;
//
//            //需要通过最初的classname来拼接其他类型的类的名称
//            String oriClassStr = classStr;
//            //类名需要加上Action后缀
//            classStr+=CLASS_SUFFIX_ACTION;
//
////            if(classStr.indexOf('.')!=-1)
////            {
////                if(classStr.indexOf('.')!=-1)
////                {
////                    packageStr = classStr.substring(0,classStr.lastIndexOf('.'));
////                    classStr = classStr.substring(classStr.lastIndexOf('.')+1);
////                }
////            }
//            sb.append("package ").append(packageStr).append(";\n");
//
//
//
//
//            /*
//             * 导入相关的类
//             * */
//            sb.append("import java.util.List;\n");
//            sb.append("import javax.servlet.http.HttpServletRequest;\n");
//            sb.append("import javax.servlet.http.HttpServletResponse;\n");
//            sb.append("import org.springframework.stereotype.Controller;\n");
//            sb.append("import com.zchl.hardware.cloud.openplatform.mqtt.broker.webadmin.servlet.BaseAction;\n");
//            sb.append("import com.zchl.hardware.cloud.openplatform.mqtt.broker.webadmin.util.ApplicationContextUtil;\n");
//
//            sb.append("import "+oriPackageStr+"."+PACKAGE_PREFIX_BEAN+"."+oriClassStr+CLASS_SUFFIX_BEAN+";\n");
//            sb.append("import "+oriPackageStr+"."+PACKAGE_PREFIX_MAPPER+"."+oriClassStr+CLASS_SUFFIX_MAPPER+";\n");
//            sb.append("import "+oriPackageStr+"."+PACKAGE_PREFIX_SEARCHBEAN+"."+oriClassStr+CLASS_SUFFIX_SEARCHBEAN+";\n");
//            sb.append("import "+oriPackageStr+"."+PACKAGE_PREFIX_VIEWBEAN+"."+oriClassStr+CLASS_SUFFIX_VIEWBEAN+";\n");
//            //controller标识
//            sb.append("@Controller\n");
//
//
//
//
//
//            sb.append("public class ").append(classStr).append(" extends BaseAction").append("\n{\n");
//
//            //实现getListCount方法
//            sb.append("\t@Override\n ");
//            sb.append("\tprotected Integer getListCount(Object cond)\n");
//            sb.append("\t{\n");
//            sb.append("\t\t").append(oriClassStr+CLASS_SUFFIX_MAPPER).append(" mapper = ApplicationContextUtil.getMapper(").append(oriClassStr+CLASS_SUFFIX_MAPPER).append(".class);\n");
//            sb.append("\t\treturn mapper.listCount((").append(oriClassStr+CLASS_SUFFIX_SEARCHBEAN).append(")cond);\n");
//            sb.append("\t}\n");
//
//            //实现getListData方法
//            sb.append("\t@Override\n ");
//            sb.append("\t@SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n");
//            sb.append("\tprotected List<Object> getListData(Object cond)\n");
//            sb.append("\t{\n");
//            sb.append("\t\t").append(oriClassStr+CLASS_SUFFIX_MAPPER).append(" mapper = ApplicationContextUtil.getMapper(").append(oriClassStr+CLASS_SUFFIX_MAPPER).append(".class);\n");
//            sb.append("\t\t return (List)mapper.list((").append(oriClassStr+CLASS_SUFFIX_SEARCHBEAN).append(")cond);\n");
//            sb.append("\t}\n");
//
//
//
//
//
//            sb.append("\n}");
//            File f = new File(MainFrame.config.get(Constant.SRCPATH));
//            f = new File(f,packageStr.replace('.', File.separatorChar));
//            if(!f.exists())
//                f.mkdirs();
//            f = new File(f,classStr+".java");
//            try {
//                PrintWriter fw = new PrintWriter(f,MainFrame.config.get(Constant.ENCODE));
//                fw.append(sb.toString());
//                fw.close();
//
//            } catch (IOException e1) {
//
//                e1.printStackTrace();
//                throw e1;
//            }
//        }
//	}


    private List<CommonTypeCouple> getCommonTypeCouples() {
        List<CommonTypeCouple> commonTypeCouples = new ArrayList<>();
        int count = model.getRowCount();
        for (int i = 0; i < count; i++) {
            if (!model.getValueAt(i, COL_INDEX_PROPERTY_NAME).equals(""))//如果有输入变量名
            {
                String common = "";
                if (!model.getValueAt(i, COL_INDEX_REMARK).equals("")) {

                    //common = "\t/**\n\t * " + model.getValueAt(i, 4).toString()+"\n\t */\n";
                    CommonTypeCouple commonTypeCouple = new CommonTypeCouple();
                    commonTypeCouple.setCommon(model.getValueAt(i, COL_INDEX_REMARK).toString());
                    commonTypeCouple.setType(model.getValueAt(i, COL_INDEX_TYPE).toString());
                    commonTypeCouple.setProperty(model.getValueAt(i, COL_INDEX_PROPERTY_NAME).toString());
                    commonTypeCouples.add(commonTypeCouple);
                }
            }
        }

        List<CommonTypeCouple> matchedCommonTypeCouples = new ArrayList<>();
        for (CommonTypeCouple commonTypeCouple : commonTypeCouples) {

            boolean ret = false;
            String common = commonTypeCouple.getCommon();
            String[] commons = common.split("#");

            for (int i = 1; i < commons.length; i++) {
                ret = true;

                String constant = commons[i];
                String[] constants = constant.split(":");

                //格式不符合，则跳过
                if (constants.length != 3) {
                    ret = false;
                    break;
                }
            }
            if (ret) {
                matchedCommonTypeCouples.add(commonTypeCouple);
            }
        }
        return matchedCommonTypeCouples;
    }

    private void checkAutoCodeAnnotation(ActionEvent e, MainFrame frame) {

        String packageName = MainFrame.config.get(Constant.ANNOTATION_PACKAGE);


        File f = new File(MainFrame.config.get(Constant.SRC_ROOT_PATH));
        f = new File(f, packageName.replace('.', File.separatorChar));
        if (!f.exists())
            f.mkdirs();
        f = new File(f, CLASS_NAME_AUTOCODE + ".java");

        //如果文件已经存在，则不做处理
        if (f.exists()) {
            return;
        }

        //生成autocode的注解
        StringBuilder sb = new StringBuilder();
        sb.append("package " + packageName + ";\n\n");
        sb.append("import java.lang.annotation.ElementType;\n");
        sb.append("import java.lang.annotation.Retention;\n");
        sb.append("import java.lang.annotation.RetentionPolicy;\n");
        sb.append("import java.lang.annotation.Target;\n\n\n\n");
        sb.append("@Retention(RetentionPolicy.RUNTIME)\n");
        sb.append("@Target({ElementType.METHOD,ElementType.FIELD})\n");
        sb.append("public @interface " + CLASS_NAME_AUTOCODE + " {\n\n");
        sb.append("}\n");


        try {
            PrintWriter fw = new PrintWriter(f, MainFrame.config.get(Constant.ENCODE));
            fw.append(sb.toString());
            fw.close();


        } catch (IOException e1) {

            e1.printStackTrace();
            throw new RuntimeException(e1);
        }


    }

    /*
     * 生成bean类
     * */
    private void generateBeanFile(ActionEvent e, MainFrame frame) throws Throwable {

        if (jtfClass.getText().equals("")) {
            JOptionPane.showMessageDialog(frame, resourceBuddle.getString("InputClassName"));
            jtfClass.requestFocus();
        } else if (model.getRowCount() == 0) {
            JOptionPane.showMessageDialog(frame, resourceBuddle.getString("NoData"));
        } else {
            StringBuilder sb = new StringBuilder();
            String classStr = jtfClass.getText();
            if (classStr.endsWith(".java")) {
                classStr = classStr.substring(0, classStr.indexOf(".java"));
            }

            //class名中不能包含包名
            if (classStr.indexOf('.') >= 0) {
                JOptionPane.showMessageDialog(frame, "类名中不能包含包名!");
                jtfClass.requestFocus();
                return;
            }
            String oriClassStr = classStr;
            classStr += CLASS_SUFFIX_BEAN;
            //String packageStr = jtfPackage.getText();
            String packageStr = MainFrame.config.get(Constant.BEAN_PACKAGE);
            String oriPackageStr = packageStr;
            //packageStr+="."+PACKAGE_PREFIX_BEAN;
//               if(classStr.indexOf('.')!=-1)
//               {
//                   if(classStr.indexOf('.')!=-1)
//                   {
//                       packageStr = classStr.substring(0,classStr.lastIndexOf('.'));
//                       classStr = classStr.substring(classStr.lastIndexOf('.')+1);
//                   }
//               }

            //获取原来文件中需要保留的信息
            String filePath = MainFrame.config.get(Constant.SRC_ROOT_PATH);
            filePath += File.separator + packageStr.replace('.', File.separatorChar) + File.separator + classStr + ".java";
            Map<String, List<String>> savedMap = JavaSourceParserUtil.getNotAutoCode(filePath);
            List<String> savedImports = savedMap.get("import");
            if (savedImports == null) {
                savedImports = new ArrayList<String>();
            }

            List<String> savedFields = savedMap.get("field");
            if (savedFields == null) {
                savedFields = new ArrayList<String>();
            }

            List<String> savedMethods = savedMap.get("method");
            if (savedMethods == null) {
                savedMethods = new ArrayList<String>();
            }


            ArrayList<String> listVar = new ArrayList<>();
            ArrayList<String> listMethod = new ArrayList<>();
            ArrayList<String> listCommon = new ArrayList<>();
            //数据库中字段的类型以及对应的common
            //用于生成常量
            //需要生成常量的common的格式为 ${字段含义}#${常量值}:${英文描述}:${中文描述}#${常量值}:${英文描述}:${中文描述}


            int count = model.getRowCount();
            /**
             *
             */
            for (int i = 0; i < count; i++) {
                if (!model.getValueAt(i, COL_INDEX_PROPERTY_NAME).equals(""))//如果有输入变量名
                {
                    String common = "";
                    if (!model.getValueAt(i, COL_INDEX_REMARK).equals("")) {

                        common = "\t/**\n\t * " + model.getValueAt(i, COL_INDEX_REMARK).toString() + "\n\t */\n";
//                           CommonTypeCouple commonTypeCouple = new CommonTypeCouple();
//                           commonTypeCouple.setCommon(model.getValueAt(i, 4).toString());
//                           commonTypeCouple.setType(model.getValueAt(i, 1).toString());
//                           commonTypeCouple.setProperty(model.getValueAt(i, COL_INDEX_PROPERTY_NAME).toString());
//                           commonTypeCouples.add(commonTypeCouple);
                    }
                    listCommon.add(common);
                    StringBuilder sb2 = new StringBuilder();
                    sb2.append("\t" + autoCodeAnnotation + "\n");
                    sb2.append("\t");
                    if (!model.getValueAt(i, COL_INDEX_DECORATOR).equals("")) {
                        sb2.append(model.getValueAt(i, COL_INDEX_DECORATOR).toString() + " ");
                    }
                    sb2.append(model.getValueAt(i, COL_INDEX_TYPE).toString() + " ");
                    sb2.append(model.getValueAt(i, COL_INDEX_PROPERTY_NAME).toString() + ";\n");
                    listVar.add(sb2.toString());
                    sb2 = new StringBuilder();
                    sb2.append("\t/**\n\t*设置" + model.getValueAt(i, COL_INDEX_REMARK).toString() + "\n\t*/\n");
                    sb2.append("\t" + autoCodeAnnotation + "\n");
                    sb2.append("\tpublic void set").append(firstUpper(model.getValueAt(i, COL_INDEX_PROPERTY_NAME).toString())).append("(").
                            append(model.getValueAt(i, COL_INDEX_TYPE)).append(" ").append(model.getValueAt(i, COL_INDEX_PROPERTY_NAME))
                            .append("){\n");
                    sb2.append("\t\tthis.").append(model.getValueAt(i, COL_INDEX_PROPERTY_NAME)).append(" = ").append(model.getValueAt(i, COL_INDEX_PROPERTY_NAME)).append(";\n");
                    sb2.append("\t}\n");
                    sb2.append("\t/**\n\t*获取" + model.getValueAt(i, COL_INDEX_REMARK).toString() + "\n\t*/\n");
                    sb2.append("\t" + autoCodeAnnotation + "\n");
                    sb2.append("\tpublic " + model.getValueAt(i, COL_INDEX_TYPE).toString() + " get").append(firstUpper(model.getValueAt(i, COL_INDEX_PROPERTY_NAME).toString())).append("(){\n");
                    sb2.append("\t\treturn ").append(model.getValueAt(i, COL_INDEX_PROPERTY_NAME)).append(";\n");
                    sb2.append("\t}\n");
                    listMethod.add(sb2.toString());
                }
            }


            //过滤掉不是常量定义的common

            List<CommonTypeCouple> commonTypeCouples = getCommonTypeCouples();
            sb.append("package ").append(packageStr).append(";\n");
            if (isIncludeTimestamp()) {
                sb.append("import java.sql.Timestamp;\n");
            }
            if (isIncludeDecimal()) {
                sb.append("import java.math.BigDecimal;\n");
            }
            sb.append("import " + autoCodeReference + ";\n");

            sb.append("import io.swagger.annotations.ApiModel;\n");
            sb.append("import io.swagger.annotations.ApiModelProperty;\n");


            if (!commonTypeCouples.isEmpty()) {
                sb.append("import java.util.Map;\n");
                sb.append("import java.util.HashMap;\n");
            }

            for (String str : savedImports) {
                sb.append(str);
            }

            //添加api model的注解
            sb.append("@ApiModel()\n");
            sb.append("public class ").append(classStr).append("{\n\n\n");


            if (!commonTypeCouples.isEmpty()) {

                //生成map
                for (CommonTypeCouple commonTypeCouple : commonTypeCouples) {
                    sb.append("\t" + autoCodeAnnotation + "\n");
                    sb.append("\tpublic static Map<" + commonTypeCouple.getType() + ",String>" + commonTypeCouple.getProperty() + "Map = new HashMap<>();\n\n");
                }

                sb.append("\tstatic{\n");
                //生成初始化代码
                for (CommonTypeCouple commonTypeCouple : commonTypeCouples) {

                    String common = commonTypeCouple.getCommon();
                    String[] commons = common.split("#");

                    for (int i = 1; i < commons.length; i++) {

                        String constant = commons[i];
                        String[] constants = constant.split(":");

                        switch (commonTypeCouple.getType()) {
                            case "Integer":
                                sb.append("\t\t" + commonTypeCouple.getProperty() + "Map.put(" + constants[0] + ",\"" + constants[2] + "\");\n");
                                break;
                            case "String":
                                sb.append("\t\t" + commonTypeCouple.getProperty() + "Map.put(\"" + constants[0] + "\",\"" + constants[2] + "\");\n");
                                break;
                        }


                    }


                }
                sb.append("\t}\n\n");
            }


            //先生成常量的定义
            for (CommonTypeCouple commonTypeCouple : commonTypeCouples) {

                //分解common
                String common = commonTypeCouple.getCommon();
                String[] commons = common.split("#");

                //第一个是字段的描述，从第二个开始常量定义
                for (int i = 1; i < commons.length; i++) {

                    String constant = commons[i];
                    String[] constants = constant.split(":");

                    if (constants.length != 3) {
                        continue;
                    }


                    String constantName = commonTypeCouple.getProperty() + "_" + constants[1];
                    constantName = constantName.toUpperCase();
                    sb.append("\t/**\n\t*" + constants[2] + "\n\t*/\n");
                    sb.append("\t" + autoCodeAnnotation + "\n");
                    sb.append("\tpublic static final ").append(commonTypeCouple.getType()).append(" ").append(constantName).append(" = ");
                    switch (commonTypeCouple.getType()) {
                        case "Integer":
                            sb.append(constants[0]);
                            break;
                        case "String":
                            sb.append("\"").append(constants[0]).append("\"");
                            break;
                        default:
                            break;

                    }
                    sb.append(";\n");

                }


            }
            sb.append("\n");

            for (String str : savedFields) {
                sb.append("\t" + str);
            }


            for (int i = 0; i < listVar.size(); i++) {
                sb.append(listCommon.get(i));
                sb.append(listVar.get(i));
            }

            for (String str : savedMethods) {
                sb.append("\t" + str);
            }
            for (int i = 0; i < listMethod.size(); i++) {
                sb.append(listMethod.get(i));
            }
            sb.append("}");
            File f = new File(MainFrame.config.get(Constant.SRC_ROOT_PATH));
            f = new File(f, packageStr.replace('.', File.separatorChar));
            if (!f.exists())
                f.mkdirs();
            f = new File(f, classStr + ".java");
            try {
                PrintWriter fw = new PrintWriter(f, MainFrame.config.get(Constant.ENCODE));
                fw.append(sb.toString());
                fw.close();


            } catch (IOException e1) {

                e1.printStackTrace();
                throw e1;
            }
        }
    }


    private String firstUpper(String str) {
        if (str == null || str.equals(""))
            return str;
        return str.substring(0, 1).toUpperCase() + str.substring(1);
    }


    public static void main(String[] argvs) {
        String src = "bank_Id_source_";
        convertColNameToHumpStyle(src);


    }

    public static class ColumnPropertyCouple {
        private String column;
        private String property;

        public String getColumn() {
            return column;
        }

        public void setColumn(String column) {
            this.column = column;
        }

        public String getProperty() {
            return property;
        }

        public void setProperty(String property) {
            this.property = property;
        }
    }

    public static class CommonTypeCouple {
        private String common;
        private String type;
        private String property;

        public String getCommon() {
            return common;
        }

        public void setCommon(String common) {
            this.common = common;
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getProperty() {
            return property;
        }

        public void setProperty(String property) {
            this.property = property;
        }
    }
}